問題:
C++コードの一部がパフォーマンスの問題に悩まされています。異なる時点を簡単に記録し、結果を適応的に印刷できる軽量なソリューションを探しています(つまり、何かが1102564643ナノ秒実行されたことを知りたいのではなく、1.102秒かかったことを知りたいだけです)
解決策
マイクロベンチマークのニーズにできるだけ手間のかからないC++11エクスペリエンスを提供できるようにAutoBenchmarkを書きました。
AutoBenchmarkを使用すると、それぞれラベル付きの異なる時点を記録できます。最初の時点はこのインスタンスが構築されたときに記録されます。AutoBenchmarkは任意の数の時点をサポートします。
このクラスのインスタンスが破棄されると、すべてのベンチマーク結果が自動的に印刷されますが、構築から設定可能な時間が経過した場合のみです — これは、関数に複数の終了点があり、それ以外の場合はPrint()を複数回呼び出す必要がある場合に非常に便利です。
あるパフォーマンス目標が達成されたときにベンチマークを無視できます(例: 一部のデータポイントでのみ遅いforループがある場合、AutoBenchmarkを遅い実行のみの情報を印刷するように構成できます)。
デフォルトの動作(つまりデフォルトパラメータを持つコンストラクタ)は自動印刷を無効にします — その場合、Print()を自分で呼び出すことができます。
ヘッダー(AutoBenchmark.hpp):
/**
* AutoBenchmark v1.1
* Written by Uli Köhler
* https://techoverflow.net
*
* https://techoverflow.net/2018/03/31/autobenchmark-automatic-multi-interval-benchmarking-in-c-using-stdchrono/
*
* Published under CC0 1.0 Universal
*/
#pragma once
#include <chrono>
#include <string>
#include <limits>
#include <vector>
using namespace std;
/**
* Automatic benchmark: Allows you to record different points in time,
* each with a label. The first time point is recorded when this instance
* is constructed. This class supports an arbitrary number of time points.
*
* When an instance of this class is destructed, it will automatically
* print all the benchmark results, but only if a configurable amount
* of time has passed since its construction, allowing you to automatically
*/
class AutoBenchmark {
public:
/**
* 合計消費時間が破棄時に autoPrintThreshold 以上の場合に
* レコードを自動的に印刷するベンチマークを初期化します。
* 最後にRecord()されたラベルまでの時間のみが印刷されます。
* @param autoPrintThreshold: デストラクタが自動的に印刷するために
* 経過する必要がある秒数。デフォルトは印刷しない。
* @param benchmarkLabel: すべての結果の前に一度だけ印刷されるラベル
* @param lineLabel: 各結果行の前に印刷されるラベル(例: インデント)
*/
AutoBenchmark(double autoPrintThreshold=std::numeric_limits<double>::max(), const std::string& benchmarkLabel = "", const std::string& lineLabel = " ");
~AutoBenchmark();
/**
* データポイントを記録
*/
void Record(const std::string& label = "");
void Record(const char *label = "");
/**
* すべての時間差を印刷
*/
void Print();
/**
* ベンチマークを新しいインスタンスのようにリセット
*/
void Reset();
/**
* now() - 最初の時点を秒で返す
*/
double TotalSeconds();
private:
vector<std::chrono::system_clock::time_point> times;
vector<std::string> labels;
double autoPrintThreshold;
std::string benchmarkLabel;
std::string lineLabel;
};ソース(AutoBenchmark.cpp):
#include "AutoBenchmark.hpp"
#include <iostream>
AutoBenchmark::AutoBenchmark(double autoPrintThreshold, const std::string& benchmarkLabel, const std::string& lineLabel)
: autoPrintThreshold(autoPrintThreshold), benchmarkLabel(benchmarkLabel), lineLabel(lineLabel) {
times.push_back(chrono::system_clock::now());
labels.emplace_back("Begin"); // インデックスを同じに保つためだけに
}
AutoBenchmark::~AutoBenchmark() {
if(TotalSeconds() >= autoPrintThreshold) {
Print();
}
}
void AutoBenchmark::Record(const std::string &label) {
times.push_back(chrono::system_clock::now());
labels.emplace_back(label); // インデックスを同じに保つためだけに
}
void AutoBenchmark::Record(const char *label) {
Record(string(label));
}
void AutoBenchmark::Print() {
if(benchmarkLabel.length()) {
cout << benchmarkLabel << '\n';
}
for (size_t i = 1; i < times.size(); i++) {
// サイズ比較のための時間間隔を計算
chrono::duration<double, std::nano> ns = times[i] - times[i - 1];
chrono::duration<double, std::micro> us = times[i] - times[i - 1];
chrono::duration<double, std::milli> ms = times[i] - times[i - 1];
chrono::duration<double> s = times[i] - times[i - 1];
chrono::duration<double, std::ratio<60>> min = times[i] - times[i - 1];
chrono::duration<double, std::ratio<3600>> hrs = times[i] - times[i - 1];
// 印刷
if(ns.count() < 1000.0) {
cout << lineLabel << labels[i] << " took " << ns.count() << " ns\n";
} else if(us.count() < 1000.0) {
cout << lineLabel << labels[i] << " took " << us.count() << " μs\n";
} else if (ms.count() < 1000.0) {
cout << lineLabel << labels[i] << " took " << ms.count() << " ms\n";
} else if (s.count() < 60.0) {
cout << lineLabel << labels[i] << " took " << s.count() << " seconds\n";
} else if (min.count() < 1000.0) {
cout << lineLabel << labels[i] << " took " << min.count() << " minutes\n";
} else {
cout << lineLabel << labels[i] << " took " << hrs.count() << " hours\n";
}
}
cout << flush;
}
void AutoBenchmark::Reset() {
times.clear();
labels.clear();
times.push_back(chrono::system_clock::now());
labels.emplace_back("Begin");
}
double AutoBenchmark::TotalSeconds() {
chrono::duration s = chrono::system_clock::now() - times[0];
return s.count();
}使用例:
#include "AutoBenchmark.hpp"
void MySlowFunction() {
// >= 0.3秒かかる実行はすべて自動印刷される
AutoBenchmark myBenchmark(0.3, "Results of running MySlowFunction():");
// .. タスク1を実行 ...
myBenchmark.Record("Running task 1"); // 次のように印刷される: Running task 1 took 1.2ms
// .. タスク2を実行 ...
myBenchmark.Record("Running task 2");
// ループの例
for(size_t i = 0; ....) {
// ... ここでループ反復タスクを実行 ...
myBenchmark.Record("Loop iteration " + std::to_string(i));
}
// myBenchmarkはここで破棄されるため、MySlowFunction()が
// 戻るまでに0.3秒以上かかった場合、結果は自動的に
// coutに印刷されます。
}MySlowFunction()が全体で0.3秒以上かかった場合、AutoBenchmarkは破棄されたとき、つまりMySlowFunction()が戻ったときに結果を印刷します:
Results of running MySlowFunction():
Running task 1 took 260.826 ms
Running task 2 took 36.148 μs
Loop iteration 0 took 2.5522 seconds
Loop iteration 1 took 664.059 ms
Loop iteration 2 took 22.2772 ms
Loop iteration 3 took 57.4024 ms
Loop iteration 4 took 16.9928 ms
Loop iteration 5 took 14.0497 ms
Loop iteration 6 took 62.5218 ms