繁体   English   中英

C ++准确的计时器time.h boost :: posix_time

[英]c++ accurate timer time.h boost::posix_time

我正在尝试创建一个计时器来分析某些功能。 例如,

#include <date_time/posix_time/posix_time.hpp>

boost::posix_time::ptime t1, t2;
t1 = boost::posix_time::microsec_clock::local_time();
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
t2 = boost::posix_time::microsec_clock::local_time();

std::cout << to_simple_string(t1) << std::endl;
std::cout << to_simple_string(t2) << std::endl;

我得到的输出是这样,

2012-Mar-04 08:21:24.760019
2012-Mar-04 08:21:25.760577

实际经过的时间是1秒和558微秒,反正我可以提高这种精度,比如说在1微秒以下吗?

我也使用链接器-lrt尝试了类似的方法。

#include <time.h>
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &timer_start);
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
clock_gettime(1CLOCK_PROCESS_CPUTIME_ID, &timer_end);

但是编译器返回CLOCK_PROCESS_CPUTIME_ID的语义错误。 错误消息如下。

Description Resource    Path    Location    Type
Symbol 'CLOCK_PROCESS_CPUTIME_ID' could not be resolved _OVERVIEW.cpp   /FUTETP/BACKEND line 32 Semantic Error

请记住两件事:

  1. 由于多种原因(系统负载等), sleep()和其他对时间敏感的命令可能不准确。 您将永远无法获得1微秒的精度。 500毫秒对于计时sleep()来说还不错
  2. 如果您的系统时间是由NTP等控制的,并且在计时操作期间更改了时钟, 则会看到此信息。 如果时间回滚,则有可能获得负数(或较大的无符号数)。

顺便说一句,我不确定Boost正在使用哪种方法获取时间,但是请考虑从sys/time.h (或从time.h更新的clock_gettime()获取gettimeofday(2) )。 它返回从1970年1月1日午夜开始的时间。记录前后的时间并减去。 这是gettimeofday()的示例。

#include <sys/time.h>

#include <stdio.h>
#include <unistd.h>

unsigned int
timeDif(
    struct timeval *before,
    struct timeval *after)
{
    return ((after->tv_sec * 1000000 + after->tv_usec) - 
        (before->tv_sec * 1000000 + before->tv_usec));
}

int
main(
    int argc,
    char *argv[]) {
    struct timeval before, after;

    gettimeofday(&before, NULL);
    sleep(1);
    gettimeofday(&after, NULL);

    printf("Elapsed time: %u microseconds\n", timeDif(&before, &after));

    return (0);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM