usleep()计算经过的时间表现很奇怪 [英] usleep() to calculate elapsed time behaves weird
问题描述
我正在使用以下代码计算每次连续调用处理程序函数所花费的时间(以毫秒为单位).当我使用usleep(1000)(即1毫秒)时,每个呼叫之间的时间差为10毫秒,而当我使用usleep(1000000)(即1秒钟)时,每个呼叫之间的时间间隔令人惊讶地下降到小于1毫秒.以下是代码段:
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#include<unistd.h>
struct timeval start_time;
void handler(int);
int main()
{
struct timeval current_time;
int i=0;
gettimeofday(&start_time,0);
gettimeofday(¤t_time,0);
printf("%012.3fms: emulationbegins\n",((current_time.tv_usec-start_time.tv_usec)/1000.0));
while(i++<5)
{
usleep(1000); // compare with usleep(1000000)
handler(i);
}
return 0;
}
void handler(int i)
{
printf("In Handler %d\n",i);
struct timeval current_time;
gettimeofday(¤t_time,0);
printf("%012.3fms: Handler Called\n",((current_time.tv_usec-start_time.tv_usec)/1000.0));
return;
}
请记住,timeval
结构的tv_usec
字段永远不会达到(或超过)一百万,而是增加秒数.>
您还必须在计算中使用tv_sec
字段.
I am calculating time elapsed in milli seconds for each successive call to handler function using the code below. When i use usleep(1000) i.e. 1 ms time difference between each call is 10 ms and when i use usleep(1000000) i.e. 1 sec surprisingly time interval between each call falls down to less than 1 ms. Following is the code snippet :
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#include<unistd.h>
struct timeval start_time;
void handler(int);
int main()
{
struct timeval current_time;
int i=0;
gettimeofday(&start_time,0);
gettimeofday(¤t_time,0);
printf("%012.3fms: emulationbegins\n",((current_time.tv_usec-start_time.tv_usec)/1000.0));
while(i++<5)
{
usleep(1000); // compare with usleep(1000000)
handler(i);
}
return 0;
}
void handler(int i)
{
printf("In Handler %d\n",i);
struct timeval current_time;
gettimeofday(¤t_time,0);
printf("%012.3fms: Handler Called\n",((current_time.tv_usec-start_time.tv_usec)/1000.0));
return;
}
Remember that the tv_usec
field of the timeval
structure never goes to (or over) one million, instead the number of seconds is increased.
You have to use the tv_sec
field as well in your calculation.
这篇关于usleep()计算经过的时间表现很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!