提问人:Amish Programmer 提问时间:9/28/2009 最后编辑:Amish Programmer 更新时间:7/1/2021 访问量:93573
C++ 跨平台高分辨率计时器
C++ Cross-Platform High-Resolution Timer
问:
我希望在C++中实现一个简单的计时器机制。该代码应该在 Windows 和 Linux 中工作。分辨率应尽可能精确(至少毫秒级精度)。这将用于简单地跟踪时间的流逝,而不是实现任何类型的事件驱动设计。实现这一目标的最佳工具是什么?
答:
C++图书馆问题的第一个答案通常是 BOOST:http://www.boost.org/doc/libs/1_40_0/libs/timer/timer.htm。这能满足您的要求吗?可能不是,但这是一个开始。
问题是你想要便携式的,而定时器功能在操作系统中不是通用的。
StlSoft 开源库在 Windows 和 Linux 平台上都提供了一个非常好的计时器。如果你想让它自己实现,只需看看他们的来源。
我不确定您的要求,如果您想计算时间间隔,请参阅下面的线程
对于 C++03:
Boost.Timer 可能会起作用,但它取决于 C 函数,因此可能没有足够好的分辨率。clock
Boost.Date_Time包括之前在 Stack Overflow 上推荐的 ptime
类。请参阅其文档 和 ,但请注意其警告,即“Win32 系统通常无法通过此 API 实现微秒级分辨率”。microsec_clock::local_time
microsec_clock::universal_time
除其他外,STLsoft 还围绕特定于操作系统的 API 提供精简的跨平台(Windows 和 Linux/Unix)C++ 包装器。它的性能库有几个类可以满足您的需求。(要使其跨平台,请选择一个类似 and 命名空间中存在的类,然后使用与您的平台匹配的任何命名空间。performance_counter
winstl
unixstl
对于 C++ 11 及更高版本:
该库内置了此功能。有关详细信息,请参阅@HowardHinnant的答案。std::chrono
评论
<chrono>
<thread>
ACE库还具有便携式高分辨率定时器。
高分辨率定时器用氧气:
http://www.dre.vanderbilt.edu/Doxygen/5.7.2/html/ace/a00244.html
我已经看到这作为闭源内部解决方案实施了几次......它们都采用了解决方案,一方面是原生 Windows 高分辨率计时器,另一方面是使用 (see ) 的 Linux 内核计时器。#ifdef
struct timeval
man timeradd
你可以把它抽象出来,一些开源项目已经做到了——我看的最后一个是 CoinOR 类 CoinTimer,但肯定还有更多。
评论
为此,我强烈推荐 boost::p osix_time 库。我相信它支持各种分辨率的计时器,低至微秒
STLSoft 有一个性能库,其中包括一组计时器类,其中一些适用于 UNIX 和 Windows。
Matthew Wilson 的 STLSoft 库提供了多种计时器类型,具有一致的接口,因此您可以即插即用。这些产品包括低成本但低分辨率的定时器,以及高分辨率但高成本的定时器。还有用于测量螺纹前时间和测量每个过程时间的,以及所有测量经过时间的方法。
几年前,Dobb 博士的文章中有一篇详尽的文章介绍了它,尽管它只涵盖了 Windows 的,即 WinSTL 子项目中定义的那些。STLSoft 还在 UNIXSTL 子项目中提供了 UNIX 计时器,您可以使用“PlatformSTL”计时器,它包括适当的 UNIX 或 Windows 计时器,如下所示:
#include <platformstl/performance/performance_counter.hpp>
#include <iostream>
int main()
{
platformstl::performance_counter c;
c.start();
for(int i = 0; i < 1000000000; ++i);
c.stop();
std::cout << "time (s): " << c.get_seconds() << std::endl;
std::cout << "time (ms): " << c.get_milliseconds() << std::endl;
std::cout << "time (us): " << c.get_microseconds() << std::endl;
}
HTH
更新了旧问题的答案:
在 C++11 中,您可以使用以下方式便携地访问最高分辨率计时器:
#include <iostream>
#include <chrono>
#include "chrono_io"
int main()
{
typedef std::chrono::high_resolution_clock Clock;
auto t1 = Clock::now();
auto t2 = Clock::now();
std::cout << t2-t1 << '\n';
}
输出示例:
74 nanoseconds
“chrono_io”是缓解这些新类型的 I/O 问题的扩展,可在此处免费获得。
在boost中也有一个可用的实现(可能仍然在树干的尖端,不确定它是否已经发布)。<chrono>
更新
这是对 Ben 在下面的评论的回应,即后续调用在 VS11 中需要几毫秒。下面是一个兼容的解决方法。但是,它仅适用于 Intel 硬件,您需要进入内联汇编(执行此操作的语法因编译器而异),并且必须将计算机的时钟速度硬连接到时钟中:std::chrono::high_resolution_clock
<chrono>
#include <chrono>
struct clock
{
typedef unsigned long long rep;
typedef std::ratio<1, 2800000000> period; // My machine is 2.8 GHz
typedef std::chrono::duration<rep, period> duration;
typedef std::chrono::time_point<clock> time_point;
static const bool is_steady = true;
static time_point now() noexcept
{
unsigned lo, hi;
asm volatile("rdtsc" : "=a" (lo), "=d" (hi));
return time_point(duration(static_cast<rep>(hi) << 32 | lo));
}
private:
static
unsigned
get_clock_speed()
{
int mib[] = {CTL_HW, HW_CPU_FREQ};
const std::size_t namelen = sizeof(mib)/sizeof(mib[0]);
unsigned freq;
size_t freq_len = sizeof(freq);
if (sysctl(mib, namelen, &freq, &freq_len, nullptr, 0) != 0)
return 0;
return freq;
}
static
bool
check_invariants()
{
static_assert(1 == period::num, "period must be 1/freq");
assert(get_clock_speed() == period::den);
static_assert(std::is_same<rep, duration::rep>::value,
"rep and duration::rep must be the same type");
static_assert(std::is_same<period, duration::period>::value,
"period and duration::period must be the same type");
static_assert(std::is_same<duration, time_point::duration>::value,
"duration and time_point::duration must be the same type");
return true;
}
static const bool invariants;
};
const bool clock::invariants = clock::check_invariants();
所以它不是便携式的。但是,如果您想在自己的英特尔硬件上尝试使用高分辨率时钟,那么没有比这更精细的了。尽管需要预先警告,但今天的时钟速度可以动态变化(它们并不是真正的编译时常数)。使用多处理器机器,您甚至可以从不同的处理器获取时间戳。但是,在我的硬件上的实验仍然运行良好。如果您坚持毫秒级分辨率,这可能是一种解决方法。
此时钟的持续时间取决于 CPU 的时钟速度(如您报告的那样)。也就是说,对我来说,这个时钟每 1/2,800,000,000 秒滴答作响一次。如果需要,可以使用以下命令将其转换为纳秒(例如):
using std::chrono::nanoseconds;
using std::chrono::duration_cast;
auto t0 = clock::now();
auto t1 = clock::now();
nanoseconds ns = duration_cast<nanoseconds>(t1-t0);
转换将截断 cpu 周期的分数以形成纳秒。其他舍入模式是可能的,但这是一个不同的主题。
对我来说,这将返回低至 18 个时钟滴答的持续时间,截断为 6 纳秒。
我在上面的时钟上添加了一些“不变检查”,其中最重要的是检查机器是否正确。同样,这不是可移植代码,但如果你正在使用这个时钟,你已经承诺了。此处显示的私有函数获取 OS X 上的最大 cpu 频率,该频率应与 的常量分母相同。clock::period
get_clock_speed()
clock::period
当您将此代码移植到新计算机时,添加此代码将节省一点调试时间,而忘记将其更新为新计算机的速度。所有检查都是在编译时或程序启动时完成的。因此,它丝毫不会影响性能。clock::period
clock::now()
评论
high_resolution_clock
如果在项目中使用Qt框架,最好的解决方案可能是使用QElapsedTimer。
SDL2 具有出色的跨平台高分辨率计时器。但是,如果您需要亚毫秒级的精度,我在这里编写了一个非常小的跨平台计时器库。 它与C++03和C++11/更高版本的C++兼容。
来晚了,但我正在使用一个还不能升级到 c++11 的遗留代码库。我们团队中没有人非常精通 c++,因此添加像 STL 这样的库被证明是困难的(除了其他人对部署问题的潜在担忧之外)。我真的需要一个非常简单的跨平台计时器,它可以独立存在,除了基本的标准系统库之外,没有任何内容。这是我发现的:
http://www.songho.ca/misc/timer/timer.html
在这里重新发布整个源代码,这样如果网站死了,它就不会丢失:
//////////////////////////////////////////////////////////////////////////////
// Timer.cpp
// =========
// High Resolution Timer.
// This timer is able to measure the elapsed time with 1 micro-second accuracy
// in both Windows, Linux and Unix system
//
// AUTHOR: Song Ho Ahn ([email protected]) - http://www.songho.ca/misc/timer/timer.html
// CREATED: 2003-01-13
// UPDATED: 2017-03-30
//
// Copyright (c) 2003 Song Ho Ahn
//////////////////////////////////////////////////////////////////////////////
#include "Timer.h"
#include <stdlib.h>
///////////////////////////////////////////////////////////////////////////////
// constructor
///////////////////////////////////////////////////////////////////////////////
Timer::Timer()
{
#if defined(WIN32) || defined(_WIN32)
QueryPerformanceFrequency(&frequency);
startCount.QuadPart = 0;
endCount.QuadPart = 0;
#else
startCount.tv_sec = startCount.tv_usec = 0;
endCount.tv_sec = endCount.tv_usec = 0;
#endif
stopped = 0;
startTimeInMicroSec = 0;
endTimeInMicroSec = 0;
}
///////////////////////////////////////////////////////////////////////////////
// distructor
///////////////////////////////////////////////////////////////////////////////
Timer::~Timer()
{
}
///////////////////////////////////////////////////////////////////////////////
// start timer.
// startCount will be set at this point.
///////////////////////////////////////////////////////////////////////////////
void Timer::start()
{
stopped = 0; // reset stop flag
#if defined(WIN32) || defined(_WIN32)
QueryPerformanceCounter(&startCount);
#else
gettimeofday(&startCount, NULL);
#endif
}
///////////////////////////////////////////////////////////////////////////////
// stop the timer.
// endCount will be set at this point.
///////////////////////////////////////////////////////////////////////////////
void Timer::stop()
{
stopped = 1; // set timer stopped flag
#if defined(WIN32) || defined(_WIN32)
QueryPerformanceCounter(&endCount);
#else
gettimeofday(&endCount, NULL);
#endif
}
///////////////////////////////////////////////////////////////////////////////
// compute elapsed time in micro-second resolution.
// other getElapsedTime will call this first, then convert to correspond resolution.
///////////////////////////////////////////////////////////////////////////////
double Timer::getElapsedTimeInMicroSec()
{
#if defined(WIN32) || defined(_WIN32)
if(!stopped)
QueryPerformanceCounter(&endCount);
startTimeInMicroSec = startCount.QuadPart * (1000000.0 / frequency.QuadPart);
endTimeInMicroSec = endCount.QuadPart * (1000000.0 / frequency.QuadPart);
#else
if(!stopped)
gettimeofday(&endCount, NULL);
startTimeInMicroSec = (startCount.tv_sec * 1000000.0) + startCount.tv_usec;
endTimeInMicroSec = (endCount.tv_sec * 1000000.0) + endCount.tv_usec;
#endif
return endTimeInMicroSec - startTimeInMicroSec;
}
///////////////////////////////////////////////////////////////////////////////
// divide elapsedTimeInMicroSec by 1000
///////////////////////////////////////////////////////////////////////////////
double Timer::getElapsedTimeInMilliSec()
{
return this->getElapsedTimeInMicroSec() * 0.001;
}
///////////////////////////////////////////////////////////////////////////////
// divide elapsedTimeInMicroSec by 1000000
///////////////////////////////////////////////////////////////////////////////
double Timer::getElapsedTimeInSec()
{
return this->getElapsedTimeInMicroSec() * 0.000001;
}
///////////////////////////////////////////////////////////////////////////////
// same as getElapsedTimeInSec()
///////////////////////////////////////////////////////////////////////////////
double Timer::getElapsedTime()
{
return this->getElapsedTimeInSec();
}
和头文件:
//////////////////////////////////////////////////////////////////////////////
// Timer.h
// =======
// High Resolution Timer.
// This timer is able to measure the elapsed time with 1 micro-second accuracy
// in both Windows, Linux and Unix system
//
// AUTHOR: Song Ho Ahn ([email protected]) - http://www.songho.ca/misc/timer/timer.html
// CREATED: 2003-01-13
// UPDATED: 2017-03-30
//
// Copyright (c) 2003 Song Ho Ahn
//////////////////////////////////////////////////////////////////////////////
#ifndef TIMER_H_DEF
#define TIMER_H_DEF
#if defined(WIN32) || defined(_WIN32) // Windows system specific
#include <windows.h>
#else // Unix based system specific
#include <sys/time.h>
#endif
class Timer
{
public:
Timer(); // default constructor
~Timer(); // default destructor
void start(); // start timer
void stop(); // stop the timer
double getElapsedTime(); // get elapsed time in second
double getElapsedTimeInSec(); // get elapsed time in second (same as getElapsedTime)
double getElapsedTimeInMilliSec(); // get elapsed time in milli-second
double getElapsedTimeInMicroSec(); // get elapsed time in micro-second
protected:
private:
double startTimeInMicroSec; // starting time in micro-second
double endTimeInMicroSec; // ending time in micro-second
int stopped; // stop flag
#if defined(WIN32) || defined(_WIN32)
LARGE_INTEGER frequency; // ticks per second
LARGE_INTEGER startCount; //
LARGE_INTEGER endCount; //
#else
timeval startCount; //
timeval endCount; //
#endif
};
#endif // TIMER_H_DEF
我发现这看起来很有前途,而且非常简单,不确定是否有任何缺点:
https://gist.github.com/ForeverZer0/0a4f80fc02b96e19380ebb7a3debbee5
/* ----------------------------------------------------------------------- */
/*
Easy embeddable cross-platform high resolution timer function. For each
platform we select the high resolution timer. You can call the 'ns()'
function in your file after embedding this.
*/
#include <stdint.h>
#if defined(__linux)
# define HAVE_POSIX_TIMER
# include <time.h>
# ifdef CLOCK_MONOTONIC
# define CLOCKID CLOCK_MONOTONIC
# else
# define CLOCKID CLOCK_REALTIME
# endif
#elif defined(__APPLE__)
# define HAVE_MACH_TIMER
# include <mach/mach_time.h>
#elif defined(_WIN32)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif
static uint64_t ns() {
static uint64_t is_init = 0;
#if defined(__APPLE__)
static mach_timebase_info_data_t info;
if (0 == is_init) {
mach_timebase_info(&info);
is_init = 1;
}
uint64_t now;
now = mach_absolute_time();
now *= info.numer;
now /= info.denom;
return now;
#elif defined(__linux)
static struct timespec linux_rate;
if (0 == is_init) {
clock_getres(CLOCKID, &linux_rate);
is_init = 1;
}
uint64_t now;
struct timespec spec;
clock_gettime(CLOCKID, &spec);
now = spec.tv_sec * 1.0e9 + spec.tv_nsec;
return now;
#elif defined(_WIN32)
static LARGE_INTEGER win_frequency;
if (0 == is_init) {
QueryPerformanceFrequency(&win_frequency);
is_init = 1;
}
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return (uint64_t) ((1e9 * now.QuadPart) / win_frequency.QuadPart);
#endif
}
/* ----------------------------------------------------------------------- */-------------------------------- */
评论
(at least millisecond accuracy)