Joh*_*ohn 7 c++ linux benchmarking clock gettimeofday
我真的不想描述,因为我想要在不同的简单功能上做很多不同的小基准测试.对于我的生活,我找不到一种方法来记录C++中的毫秒数,顺便说一句,我正在使用Linux.
你能否建议以毫秒为单位获取系统时钟的方法(如果我找不到简单的方法,我可以用几秒钟来解决......)以及它们包含在哪个标题中?
M. *_* E. 21
使用头文件中的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);
}
};
Run Code Online (Sandbox Code Playgroud)
例如:
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是x86 CPU,则可以使用rdtsc汇编程序指令http://en.wikipedia.org/wiki/Rdtsc,以便在执行两个(或更多)命令之间获得CPU时钟数.但是:1.所有rdtsc命令应该在相同的CPU内核上运行(如果你有多核CPU的话).2. CPU应以恒定的时钟频率运行(应禁用CPU电源管理).
迪马