c++ - C++ 中精确到毫秒的基准测试?

标签 c++ linux benchmarking clock gettimeofday

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

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

最佳答案

使用 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);
    }
};

例如:

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

关于c++ - C++ 中精确到毫秒的基准测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3797708/

相关文章:

c++ - 如何从主应用程序的 GetInstance 获取引用?

c++ - C++中元组元素类型的大小总和

c++ - 如何在控制台上显示 map 的内容?

c++ - 运行简单的单线程 C++ 程序时,是否可以消除 Linux 机器的抖动?

algorithm - 用于在多核 x86 CPU 上进行测试的并行算法基准测试工具

c++ - AppInit_DLL 能否用于从 Ws2_32.dll 挂接 API?

linux - ffmpeg 实时转码更快的替代方案?

linux - 如何使用客户端 $Hostname 在 nxlog 服务器中自动创建目录?

linux - 使用 grep 搜索文件内容以获取行开头的特定数量的字符

linux - 在 Linux 上进行基准测试时测量温度