我正在使用clock函数来打印当前程序的执行时间。但是输出的结果是错误的。我希望能够以秒,毫秒和微秒的形式显示时间。
#include <stdio.h>
#include <unistd.h>
#include <time.h>
int main()
{
clock_t start = clock();
sleep(3);
clock_t end = clock();
double time_taken = (double)(end - start)/CLOCKS_PER_SEC; // in seconds
printf("time program took %f seconds to execute \n", time_taken);
return 0;
}
time ./time
time program took 0.081000 seconds to execute
real 0m3.002s
user 0m0.000s
sys 0m0.002s
我期望输出大约在3秒左右,但结果显示错误。 正如你所看到的如果我使用Linux命令time运行此程序,我得到了正确的时间,我想用我的c程序显示相同的时间。
clock_gettime()
函数(https://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html)。 - pmgclock()
。 - Jonathan Leffler