简体   繁体   English

C ++中毫秒级准确的基准测试?

[英]millisecond-accurate benchmarking in C++?

I do not really wish to profile because I was wanting to do many different small benchmarks on different simple functions. 我真的不想分析,因为我想对不同的简单函数进行许多不同的小型基准测试。 For the life of me I cannot find a way to record the amount of milliseconds in C++, I am using Linux by the way. 在我的一生中,我无法找到一种方法来记录C ++中的毫秒数,因此我正在使用Linux。

Can you suggest the method to get the system clock in milliseconds (I may settle with seconds if I cannot find an easy way..) and what header they are included in? 您能否建议以毫秒为单位获取系统时钟的方法(如果找不到简单的方法,我可能会用几秒钟来解决。)以及它们包含在哪个标头中?

using gettimeofday function from sys/time.h header file, i use this class: 使用sys/time.h头文件中的gettimeofday函数,我使用此类:

#include <cstdlib>
#include <sys/time.h>

class Timer
{
    timeval timer[2];

  public:

    timeval start()
    {
        gettimeofday(&this->timer[0], NULL);
        return this->timer[0];
    }

    timeval stop()
    {
        gettimeofday(&this->timer[1], NULL);
        return this->timer[1];
    }

    int duration() const
    {
        int secs(this->timer[1].tv_sec - this->timer[0].tv_sec);
        int usecs(this->timer[1].tv_usec - this->timer[0].tv_usec);

        if(usecs < 0)
        {
            --secs;
            usecs += 1000000;
        }

        return static_cast<int>(secs * 1000 + usecs / 1000.0 + 0.5);
    }
};

for example: 例如:

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    Timer tm;
    std::ostringstream ooo;
    std::string str;

    tm.start();
    for(int i = 0; i < 10000000; ++i)
    {
        ooo << "This is a string. ";
    }
    tm.stop();
    std::cout << "std::ostingstream -> " << tm.duration() << std::endl;

    tm.start();
    for(int i = 0; i < 10000000; ++i)
    {
        str += "This is a string. ";
    }
    tm.stop();
    std::cout << "std::string -> " << tm.duration() << std::endl;
}

If you are using x86 CPU, you can use rdtsc assembler instructions http://en.wikipedia.org/wiki/Rdtsc in order to get number of CPU clocks between execution of two (or more) commands. 如果您使用的是x86 CPU,则可以使用rdtsc汇编程序说明http://en.wikipedia.org/wiki/Rdtsc来获取执行两个(或更多)命令之间的CPU时钟数。 But: 1. All rdtsc commands should run on same CPU core (in case if you have multi core CPU). 但是:1.所有rdtsc命令都应在同一CPU内核上运行(如果您有多核CPU)。 2. CPU should run in constant clock frequency (CPU power management should be disabled). 2. CPU应该以恒定的时钟频率运行(应该禁用CPU电源管理)。

Dima 迪玛

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

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