我正在尝试创建一个计时器来分析某些功能。例如,
#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
最佳答案
请记住两件事:
sleep()
和其他对时间敏感的命令可能由于多种原因(系统负载等)而变得不准确。你永远不会得到 1 微秒以内的精度。 500 微秒对于计时sleep()
来说还算不错
- 如果你的系统时间是由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/