Last active
September 18, 2023 12:49
-
-
Save jm4R/7ba7de23c99c4f7b64bca09d3b0a2be9 to your computer and use it in GitHub Desktop.
Easy benchmark boilerplate that most often works as expected
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <chrono> | |
#include <string> | |
class benchmark | |
{ | |
using clock = std::chrono::steady_clock; | |
public: | |
benchmark(std::string location, unsigned line) | |
: location_{std::move(location)}, line_{line}, start_{clock::now()} | |
{ | |
} | |
~benchmark() | |
{ | |
const auto stop = clock::now(); | |
const auto diff = stop - start_; | |
if (diff < std::chrono::milliseconds{2}) | |
{ | |
std::printf( | |
"BENCHMARK: %s:%u | \t\t %dμs\n", location_.c_str(), line_, | |
int(std::chrono::duration_cast<std::chrono::microseconds>(diff) | |
.count())); | |
} | |
else | |
{ | |
std::printf( | |
"BENCHMARK: %s:%u | \t\t %dms\n", location_.c_str(), line_, | |
int(std::chrono::duration_cast<std::chrono::milliseconds>(diff) | |
.count())); | |
} | |
std::fflush(stdout); | |
} | |
private: | |
const std::string location_; | |
const unsigned line_; | |
const clock::time_point start_; | |
}; | |
#define B_MERGE(a, b) a##b | |
#define B_LABEL(a) B_MERGE(bench_obj_, a) | |
#define B_OBJNAME B_LABEL(__LINE__) | |
#define BENCHMARK \ | |
const auto B_OBJNAME = benchmark \ | |
{ \ | |
__PRETTY_FUNCTION__, __LINE__ \ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment