如何使用 gettimeofday 来测量时间的流逝?
我只被允许使用这个函数,我正在尝试找出一种方法来计算经过的时间,有什么想法吗?我很困惑..
# include <sys/types.h>
# include <sys/time.h>
# include <stdio.h>
# include <unistd.h>
int main(int argc, char* argv[])
{
struct timeval now;
struct timeval start;
int t_now;
int t_stop;
int t_start;
int i;
gettimeofday(&start, NULL);
t_start = start.tv_usec / 1000;
t_stop = t_start + 200;
while (42)
{
usleep(2000);
gettimeofday(&now, NULL);
t_now = now.tv_usec / 1000;
if (t_now - t_stop > -1)
{
break;
}
printf ("%d\n", t_now);
usleep(2000);
}
return 0;
}
我正在这样做,但它会继续循环,并且不会停止..
I'm only allowed to use this function and I'm trying to figure out a way to calculate time elapsed, any ideas? I'm confused..
# include <sys/types.h>
# include <sys/time.h>
# include <stdio.h>
# include <unistd.h>
int main(int argc, char* argv[])
{
struct timeval now;
struct timeval start;
int t_now;
int t_stop;
int t_start;
int i;
gettimeofday(&start, NULL);
t_start = start.tv_usec / 1000;
t_stop = t_start + 200;
while (42)
{
usleep(2000);
gettimeofday(&now, NULL);
t_now = now.tv_usec / 1000;
if (t_now - t_stop > -1)
{
break;
}
printf ("%d\n", t_now);
usleep(2000);
}
return 0;
}
I was doing this but it will keep looping, and won't stop..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这
没有达到您的预期。 tv_usec 只有几分之一秒,您需要
获取总毫秒
this
isnt doing what you expect. tv_usec only has fractions of a second, you need
to get total msec