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

标签 c++ gcc g++

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

#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. 来说还算不错
  3. 如果你的系统时间是由NTP等控制的,在你的计时操作过程中时钟发生了变化,你看到这个。如果时间回滚,有可能得到一个负数(或大的无符号数)。

顺便说一句,我不确定 Boost 使用什么方法来获取时间,但考虑 sys/time.h 中的 gettimeofday(2)(或较新的 clock_gettime() 来自 time.h)。它返回自 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);
}

关于C++ 精确计时器 time.h boost::posix_time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9555700/

相关文章:

c++ - 在 C++ (g++) 中使用 errno 作为异常参数的意外控制流(编译器错误?)

c++ - Mac(或 C++)连接到二进制 WCF

c - 恢复 C (gcc) 中的递归函数?

gcc - C C++ 链接错误

c++ - 尝试链接到 SDL_ttf 共享对象文件时 g++ 中的链接器错误

c++ - MacOS X - 编译插件

c++ - SFINAE 和参数数量

c - Scanf 在 C 中跳过每隔一个 while 循环

c++ - 如何使用 OpenSSL 编译一个简单的程序?

c++ - g++ - 无法链接到使用 VS2012 构建的静态库