gettimeofday函数获得的微秒数是从什么时候开始算的,另为什么usleep(20)前后获得的微秒数之差会大于20,而且不是一个固定值

app_3 2011-10-26 10:14:17
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{

struct timeval before_usleep;
struct timeval after_usleep;


gettimeofday(&before_usleep,NULL);
usleep(20);

gettimeofday(&after_usleep,NULL);
printf("%d,\n%d\n",before_usleep.tv_usec,after_usleep.tv_usec);
printf("sleep time =%dms\n",after_usleep.tv_usec-before_usleep.tv_usec);
exit(0);
}


[kiongf@localhost ~]$ ./a.out
667131,
668155
sleep time =1024ms
[kiongf@localhost ~]$ ./a.out
367426,
368407
sleep time =981ms
[kiongf@localhost ~]$ ./a.out
48116,
49014
sleep time =898ms
[kiongf@localhost ~]$ ./a.out
553446,
553849
sleep time =403ms
[kiongf@localhost ~]$ ./a.out
475882,
476690
sleep time =808ms

这是我多次运行的结果。usleep的差值越来越大从70ms-981ms
~
...全文
390 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2011-10-26
  • 打赏
  • 举报
回复
楼主怎么只计算微秒的差值啊,我擦,万一正好20微秒内跨过了整秒你怎么办.

应该是:

if(end.tv_usec<begin.tv_usec){end.tv_usec+=1000000;end.tv_sec--;}

然后计算end.tv_usec-begin.tv_usec就是差得时间了,为了保证安全,最好计算一下:end.tv_sec-begin.tv_sec是否等于0,usleep20微秒不保证系统就一定在1秒内给你睡醒。
qq120848369 2011-10-26
  • 打赏
  • 举报
回复

int gettimeofday(struct timeval *tv, struct timezone *tz);
returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};

       The usleep() function suspends execution of the calling thread for (at least) usec microseconds.  The sleep may be lengthened slightly by any sys‐
tem activity or by the time spent processing the call or by the granularity of system timers.

ezword 2011-10-26
  • 打赏
  • 举报
回复
单位错了吧,那单位应该是微秒。

另外这种东西从系统调用到内核态本身会消耗一定的时间,应该是微秒级别的。

硬件中断会影响这个值的计算,进程调度也会影响。以上这些时间都是不确定的。

以10ms为单位计算误差应该会小些吧,呵呵

4,436

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 内核源代码研究区
社区管理员
  • 内核源代码研究区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧