c语言测机器运行时间,C语言clock()测试函数运行时间
運行環境:
win10家庭版 64位
MinGW.org GCC-6.3.0-1
以下英文解釋引自man page: man 3 clock
DESCRIPTION
The clock() function returns an approximation of processor time used by the program.
RETURN VALUE
The value returned is the CPU time used so far as a clock_t; to get the number of seconds used, divide by
CLOCKS_PER_SEC. If the processor time used is not available or its value cannot be represented, the function
returns the value (clock_t) -1.
clock()函數返回 程序占用的處理器時間粗略值, 要想獲得實際的秒數, 最后要除以CLOCKS_PER_SEC。
這個CLOCKS_PER_SEC是什么東西? 在time.h中有如下定義:
/* Number of clock ticks per second. A clock tick is the unit by which
* processor time is measured and is returned by 'clock'.
*/
#define CLOCKS_PER_SEC((clock_t)(1000))
#define CLK_TCK CLOCKS_PER_SEC
當然這個CLOCKS_PER_SEC不一定是1000, 各個系統可能不太一樣, 所以還是使用常量.
CLK_TCK也可以用, 不過已經過時了, 最好是使用CLOCKS_PER_SEC常量.
那如何用它來測試程序執行時間呢?
演示代碼:
#include
#include
int f1() {
int i;
int j;
int tmp;
int loopNum = 10000;
for (i = 0; i < loopNum; i++) {
for (j = 0; j < loopNum; j++) {
tmp = i * j;
}
}
return tmp;
}
int main(int argc, char const *argv[])
{
const int N = 1e2;
int i = 0;
clock_t start, end;
start = clock();
for (; i < N; i++) {
f1();
}
end = clock();
printf("time: %f s\n", ((double)(end - start)) / CLOCKS_PER_SEC / N);
return 0;
}
在我的電腦上運行結果為:
time: 0.222540 s
也就是說, 函數f1的平均運行時間約為0.22秒.
說明: 可以看到, 上面對f1執行了N次. 因為在大多數情況下, 被測試函數(如當前的f1)可能運行很快, 只運行一次的話由于時間太短, 結果就是0, 所以多跑幾次, 再求均值即可.
歡迎補充指正!
總結
以上是生活随笔為你收集整理的c语言测机器运行时间,C语言clock()测试函数运行时间的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言解析json报文源码,GitHub
- 下一篇: 石大在线c语言在线考试填空题答案,奥鹏石