我正在用 c 编写一些基本的东西,即执行 shell 脚本需要多长时间。
我有
gettimeofday(&start, NULL);
// code here
gettimeofday(&end, NULL);
// print end - start
我知道 timeval 结构具有我考虑的 tv_sec 和 tv_usec,但即使对于诸如“sleep 3”之类的脚本,我仍然得到 0 结束 - 开始差异。任何猜测为什么?
您应该阅读以下内容:gettimeofday() 永远不应该用于测量时间
试试clock_gettime(CLOCK_MONOTONIC, ...)
吧。
试试这个:
double dtime(){
double t;
struct timeval tv;
gettimeofday(&tv, NULL);
t = tv.tv_sec + ((double)tv.tv_usec)/1e6;
return t;
}
…
double t0 = dtime();
…
printf("Time spend: %g seconds\n", dtime()-t0);