简约的复制粘贴结构体+懒惰使用
如果想要一个可以用于快速测试的简约结构体,建议您在C++文件中的#include
后面随意复制粘贴。这是我唯一牺牲Allman风格格式的情况。
您可以在结构体的第一行轻松调整精度。可能的值为:nanoseconds
, microseconds
, milliseconds
, seconds
, minutes
, 或 hours
。
#include <chrono>
struct MeasureTime
{
using precision = std::chrono::microseconds;
std::vector<std::chrono::steady_clock::time_point> times;
std::chrono::steady_clock::time_point oneLast;
void p() {
std::cout << "Mark "
<< times.size()/2
<< ": "
<< std::chrono::duration_cast<precision>(times.back() - oneLast).count()
<< std::endl;
}
void m() {
oneLast = times.back();
times.push_back(std::chrono::steady_clock::now());
}
void t() {
m();
p();
m();
}
MeasureTime() {
times.push_back(std::chrono::steady_clock::now());
}
};
使用方法
MeasureTime m; // first time is already in memory
doFnc1();
m.t(); // Mark 1: next time, and print difference with previous mark
doFnc2();
m.t(); // Mark 2: next time, and print difference with previous mark
doStuff = doMoreStuff();
andDoItAgain = doStuff.aoeuaoeu();
m.t(); // prints 'Mark 3: 123123' etc...
标准输出结果
Mark 1: 123
Mark 2: 32
Mark 3: 433234
如果您想在执行后获得摘要
如果您想在之后获得报告,例如因为您的代码在其中还写入标准输出。那么请在结构体中添加以下函数(就在MeasureTime()函数之前):
void s() {
int i = 0;
std::chrono::steady_clock::time_point tprev;
for(auto tcur : times)
{
if(i > 0)
{
std::cout << "Mark " << i << ": "
<< std::chrono::duration_cast<precision>(tprev - tcur).count()
<< std::endl;
}
tprev = tcur;
++i;
}
}
那么你可以直接使用:
MeasureTime m;
doFnc1();
m.m();
doFnc2();
m.m();
doStuff = doMoreStuff();
andDoItAgain = doStuff.aoeuaoeu();
m.m();
m.s();
这将列出所有的标记,就像以前一样,但在执行其他代码后。请注意,不应同时使用m.s()
和m.t()
。
clock()
并不像我想象的那样快。 - Mooing Duck