日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

c语言测机器运行时间,C语言clock()测试函数运行时间

發布時間:2025/3/19 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()测试函数运行时间的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。