C ++中的毫秒准确的基准测试?
-
05-10-2019 - |
题
我真的不想概括,因为我想对不同的简单功能进行许多不同的小基准。对于我的一生,我找不到记录C ++中毫秒的方法,顺便说一句,我正在使用Linux。
您能否建议将系统时钟以毫秒获取的方法(如果找不到简单的方法,我可能会和几秒钟安顿下来。)以及它们包含在什么标题中?
解决方案
使用 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;
}
其他提示
如果您使用的是X86 CPU,则可以使用RDTSC汇编指令 http://en.wikipedia.org/wiki/rdtsc 为了在执行两个(或更多)命令之间获得CPU时钟数。但是:1。所有RDTSC命令都应在同一CPU核心上运行(如果您具有多核CPU)。 2. CPU应以恒定的时钟频率运行(CPU电源管理应禁用)。
Dima
不隶属于 StackOverflow