usleep()计算经过的时间表现很奇怪 [英] usleep() to calculate elapsed time behaves weird

查看:416
本文介绍了usleep()计算经过的时间表现很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码计算每次连续调用处理程序函数所花费的时间(以毫秒为单位).当我使用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(&current_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(&current_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(&current_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(&current_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆