我試圖使用使用clock()
linux下的測量用C執行時間如下:測量執行時間與時鐘秒用C不工作
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char const* argv[])
{
clock_t begin, end;
begin = clock();
sleep(2);
end = clock();
double spent = ((double)(end-begin))/CLOCKS_PER_SEC;
printf("%ld %ld, spent: %f\n", begin, end, spent);
return 0;
}
輸出是:
1254 1296, spent: 0.000042
文檔中說,將時鐘時間除以CLOCKS_PER_SEC
以獲得以秒爲單位的執行時間,但對於2秒sleep
,這似乎相當不正確。
有什麼問題?
'%f'爲'double',僅供參考。 –
@SouravGhosh是的,就像變量time_spent一樣。 –
@SouravGhosh,C可變功能會自動進行一定的促銷活動。其中之一是從浮動到雙倍。使用%f作爲浮點數並不是最優的,但它也不完全是錯誤的。對於%d的打印字符也是如此。 –