7

我真的不想进行分析,因为我想对不同的简单功能进行许多不同的小型基准测试。对于我的一生,我无法找到一种方法来记录 C++ 中的毫秒数,顺便说一下,我正在使用 Linux。

您能否建议以毫秒为单位获取系统时钟的方法(如果我找不到简单的方法,我可能会以秒为单位。)以及它们包含在什么标题中?

4

2 回答 2

20

使用头文件中的gettimeofday函数sys/time.h,我使用这个类:

#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);
    }
};

例如:

#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;
}
于 2010-09-26T12:12:43.460 回答
7

如果您使用的是 x86 CPU,您可以使用 rdtsc 汇编指令http://en.wikipedia.org/wiki/Rdtsc来获取执行两个(或更多)命令之间的 CPU 时钟数。但是: 1. 所有 rdtsc 命令都应该在同一个 CPU 内核上运行(如果你有多核 CPU)。2. CPU 应以恒定时钟频率运行(应禁用 CPU 电源管理)。

迪玛

于 2010-09-26T12:30:07.473 回答