C ++计算时间间隔 [英] C++ calculating time intervals

查看:205
本文介绍了C ++计算时间间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算在我的程序中发生的一些事件之间的时间间隔(在1/10秒的1秒)。因此,我使用 clock 函数来满足以下需求:

I want to calculate time intervals (in 1/10th of 1 second) between some events happening in my program. Thus I use clock function for these needs like follows:

    clock_t begin;
    clock_t now;
    clock_t diff;

    begin = clock();

    while ( 1 )
    {
        now = clock();
        diff = now - begin;
        cout << diff / CLOCKS_PER_SEC << "\n";
        //usleep ( 1000000 );
    };

我希望程序打印 0 1秒,然后 1 持续1秒,然后 2 持续1秒。等等...事实上,它打印 0 大约8秒钟,然​​后 1 大约8秒钟on ...

I expect the program to print 0 for 1 second, then 1 for 1 sec., then 2 for 1 sec. and so on... In fact it prints 0 for about 8 seconds, then 1 for about 8 seconds and so on...

顺便说一句,如果我在命令程序中添加 usleep ,每秒只打印一次,它只打印 0 所有方式...

By the way, if I add usleep in order program prints only 1 time per second, it prints only 0 all way long...

非常感谢您的帮助!

推荐答案

clock()函数返回向您的程序收取的CPU时间。当您在 usleep()电话内部被封锁时,没有时间向您收费,这使您非常清楚为什么您的时间似乎没有增加。至于为什么你似乎花了8秒的时间收取一秒钟 - 你的系统中还有其他事情,消耗CPU时间,你想消费,但你必须共享处理器。 clock()不能用于测量实时通行。

The clock() function returns the amount of CPU time charged to your program. When you are blocked inside a usleep() call, no time is being charged to you, making it very clear why your time never seems to increase. As to why you seem to be taking 8 seconds to be charged one second -- there are other things going on within your system, consuming CPU time that you would like to be consuming but you must share the processor. clock() cannot be used to measure the passage of real time.

这篇关于C ++计算时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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