我不想使用性能分析,因为我想对不同的简单函数进行多个小型基准测试。但我却找不到一种在C++中记录毫秒数的方法,顺便说一下,我正在使用Linux。
你能否建议一种获取系统时钟毫秒数(如果找不到简单的方法,我可以接受秒数)的方法,以及它们所包含的头文件?
我不想使用性能分析,因为我想对不同的简单函数进行多个小型基准测试。但我却找不到一种在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;
}
999
向下舍入到一而不是零。 - John+0.5
进行四舍五入是因为要对结果进行四舍五入,但如果结果的符号为负,则必须使用-0.5
而不是+0.5
。 - Sadeq