C++ 跨平台高分辨率计时器

C++ Cross-Platform High-Resolution Timer

提问人:Amish Programmer 提问时间:9/28/2009 最后编辑:Amish Programmer 更新时间:7/1/2021 访问量:93573

问:

我希望在C++中实现一个简单的计时器机制。该代码应该在 Windows 和 Linux 中工作。分辨率应尽可能精确(至少毫秒级精度)。这将用于简单地跟踪时间的流逝,而不是实现任何类型的事件驱动设计。实现这一目标的最佳工具是什么?

C++ 跨平台 计时器

评论

5赞 jmucchiello 9/28/2009
更具体。您是在对函数调用进行计时,还是希望在指定的时间段后接收某种信号。这些都是“简单”的计时器应用程序,但它们的实现方式却截然不同。请注意,在引号中使用“简单”:通用计算机中的计时从来都不是“简单”的。
0赞 Ciro Santilli OurBigBook.com 3/19/2016
C版本 stackoverflow.com/questions/361363/...
0赞 Eduardo Reis 11/4/2023
从CPU的角度来看,分辨率并不高。(at least millisecond accuracy)

答:

2赞 jmucchiello 9/28/2009 #1

C++图书馆问题的第一个答案通常是 BOOST:http://www.boost.org/doc/libs/1_40_0/libs/timer/timer.htm。这能满足您的要求吗?可能不是,但这是一个开始。

问题是你想要便携式的,而定时器功能在操作系统中不是通用的。

5赞 Malte Clasen 9/28/2009 #2

StlSoft 开源库在 Windows 和 Linux 平台上都提供了一个非常好的计时器。如果你想让它自己实现,只需看看他们的来源。

1赞 Satbir 9/28/2009 #3

我不确定您的要求,如果您想计算时间间隔,请参阅下面的线程

以 毫秒为单位计算 C 程序中的运行时间

44赞 Josh Kelley 9/28/2009 #4

对于 C++03

Boost.Timer 可能会起作用,但它取决于 C 函数,因此可能没有足够好的分辨率。clock

Boost.Date_Time包括之前在 Stack Overflow 上推荐的 ptime。请参阅其文档 和 ,但请注意其警告,即“Win32 系统通常无法通过此 API 实现微秒级分辨率”。microsec_clock::local_timemicrosec_clock::universal_time

除其他外,STLsoft 还围绕特定于操作系统的 API 提供精简的跨平台(Windows 和 Linux/Unix)C++ 包装器。它的性能库有几个类可以满足您的需求。(要使其跨平台,请选择一个类似 and 命名空间中存在的类,然后使用与您的平台匹配的任何命名空间。performance_counterwinstlunixstl

对于 C++ 11 及更高版本

该库内置了此功能。有关详细信息,请参阅@HowardHinnant的答案std::chrono

评论

7赞 Manu343726 5/2/2014
由于这是一个著名的问题/答案,因此更新可能会很棒。具体来说,这可以使用现代 C++ 功能以标准和可移植的方式实现,例如 和 ?如果可能,如何?<chrono><thread>
5赞 Dan 9/28/2009 #5

ACE库还具有便携式高分辨率定时器。

高分辨率定时器用氧气:
http://www.dre.vanderbilt.edu/Doxygen/5.7.2/html/ace/a00244.html

4赞 Dirk is no longer here 9/28/2009 #6

我已经看到这作为闭源内部解决方案实施了几次......它们都采用了解决方案,一方面是原生 Windows 高分辨率计时器,另一方面是使用 (see ) 的 Linux 内核计时器。#ifdefstruct timevalman timeradd

你可以把它抽象出来,一些开源项目已经做到了——我看的最后一个是 CoinOR 类 CoinTimer,但肯定还有更多。

评论

0赞 Patrick 6/22/2017
我决定走这条路。你的链接已经死了,所以我用一个仍然有效的链接发表了评论:songho.ca/misc/timer/timer.html
0赞 Dirk is no longer here 6/22/2017
啊,没有什么比对一个八年前的问题的评论:)与此同时,我很幸运地使用了 Google 的 CCTZ 库,它建立在一些更新的 C++11 习语之上。
4赞 Maciek 9/29/2009 #7

为此,我强烈推荐 boost::p osix_time 库。我相信它支持各种分辨率的计时器,低至微秒

2赞 JamieH 9/30/2009 #8

STLSoft 有一个性能库,其中包括一组计时器类,其中一些适用于 UNIX 和 Windows。

6赞 dcw 9/30/2009 #9

Matthew WilsonSTLSoft 库提供了多种计时器类型,具有一致的接口,因此您可以即插即用。这些产品包括低成本但低分辨率的定时器,以及高分辨率但高成本的定时器。还有用于测量螺纹前时间和测量每个过程时间的,以及所有测量经过时间的方法。

几年前,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

164赞 Howard Hinnant 4/2/2011 #10

更新了旧问题的答案:

在 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::periodget_clock_speed()clock::period

当您将此代码移植到新计算机时,添加此代码将节省一点调试时间,而忘记将其更新为新计算机的速度。所有检查都是在编译时或程序启动时完成的。因此,它丝毫不会影响性能。clock::periodclock::now()

评论

2赞 Petter 1/20/2012
不幸的是,在 Visual Studio 11 中,最短的非零间隔是几毫秒。high_resolution_clock
6赞 Howard Hinnant 1/20/2012
我花了几秒钟的时间才把那个水槽放进去......在时钟速度仅为几分之一纳秒的平台上,数百万纳秒。哇!!!我希望看到几分之一纳秒是可测量的平台。我以为我几十纳秒的结果并不那么令人印象深刻。
3赞 David 2/18/2013
有没有人知道在编译时获得 cpu 频率的方法?也。。。如今,CPU 频率在运行时间上不能变化吗,比如 Turbo 模式等等?也许这会使这种方法变得不可行?不过,我确实需要一个像样的 VS11 计时器,呃。
3赞 Howard Hinnant 2/18/2013
@Dave:是的,cpu 频率可以动态变化(我在回答中说过)。使用这个时,我的实验通常是围绕着我试图测量的东西的紧密循环。至少对于我的平台来说,这种紧密的循环通常会将 CPU 频率提高到最大值,而该最大值通常是编译时常数(从 CPU 规范中读出)。因此,对于这种基准测试,这可能是一种有效的技术。但显然这不是通用用途的东西。我不建议运送。仅用于调查目的。
7赞 Programmdude 3/26/2017
我使用 VS2017 在 Windows 上获得了 600-1200 纳秒,它似乎正在使用高性能计时器。所以看来这个1ms分辨率的问题不再是问题了。
0赞 László Papp 4/5/2014 #11

如果在项目中使用Qt框架,最好的解决方案可能是使用QElapsedTimer。

3赞 metamorphosis 10/29/2015 #12

SDL2 具有出色的跨平台高分辨率计时器。但是,如果您需要亚毫秒级的精度,我在这里编写了一个非常小的跨平台计时器库。 它与C++03和C++11/更高版本的C++兼容。

1赞 Patrick 6/22/2017 #13

来晚了,但我正在使用一个还不能升级到 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
3赞 Dan Bechard 2/4/2020 #14

我发现这看起来很有前途,而且非常简单,不确定是否有任何缺点:

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
}
/* ----------------------------------------------------------------------- */-------------------------------- */