如何在linux中测量时间?

时间:2013-03-03 18:47:47

标签: c linux timer

我想在给定时间参数时将数据写入文件: 例如,我得到x = 7 - >意味着接下来的7秒将一些随机数据写入文件 我这样做有些困难, 我已经尝试过使用:clock()和struct timeval但是它不起作用

我尝试过的事情:

struct timeval start, end;
gettimeofday(&start, 0);
while(  gettimeofday(&end, 0) && end.tv_sec - start.tv_sec < sec )
  {
    write....
  }

但它会停止时钟..

很想得到一些帮助。 感谢

3 个答案:

答案 0 :(得分:7)

如果getTimeOfDay成功,则返回0,然后while条件失败。尝试:

while(  (gettimeofday(&end, 0) == 0) && end.tv_sec - start.tv_sec < sec )
{
    write....
}

答案 1 :(得分:1)

考虑操作顺序...尝试在&&

的操作数周围添加parens

man:gettimeofday()

RETURN VALUE
    The `gettimeofday()` function shall return 0 and 
    no value shall be reserved to indicate an error.

在你的代码中因为gettimeofday()在循环中断时成功返回0。

以下代码使用!逻辑非运算符进行了纠正。

while(  (!gettimeofday(&end, 0)) && end.tv_sec - start.tv_sec < sec )
  {
    write....
  }

答案 2 :(得分:0)

您应该考虑使用clock_gettime代替gettimeofdayPOSIX.1-2008声称这是#include <time.h> int main() { struct timespec start, end; int sec = 10; // Number of seconds clock_gettime(CLOCK_REALTIME, &start); while( !clock_gettime(CLOCK_REALTIME, &end) && end.tv_sec - start.tv_sec < sec ) { // Write ... } }

gcc

注意:如果您正在使用g++librt来编译您的程序,则需要通过附加{{1}来链接-lrt库}}:

gcc myprogram.c -o myprogram -lrt
相关问题