[英]how to measure time in linux?
我想在给定时间参数时将数据写入文件:例如,我得到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....
}
但它会停止时钟..
我很乐意得到一些帮助。 谢谢
如果getTimeOfDay
成功,则返回0,然后您的while
条件失败。 尝试:
while( (gettimeofday(&end, 0) == 0) && end.tv_sec - start.tv_sec < sec )
{
write....
}
考虑操作顺序...尝试在&&
的操作数周围添加parens
男人: 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....
}
您应该考虑使用clock_gettime
而不是gettimeofday
,这被声称是POSIX.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++
编译程序,则需要通过附加-lrt
链接librt
库:
gcc myprogram.c -o myprogram -lrt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.