-
-
Save hirohitokato/310304 to your computer and use it in GitHub Desktop.
元ネタ:C++ で気軽に時間測定がしたい http://d.hatena.ne.jp/iwiwi/20100221/1266682598 ブロック内で標準エラー出力へ出力していたり,入れ子的に使ったりすると表示がおかしなことになってしまう問題の対策コード http://twitter.com/qnighy/status/9423778596
This file contains hidden or 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
/* | |
* 元ネタ:C++ で気軽に時間測定がしたい | |
* http://d.hatena.ne.jp/iwiwi/20100221/1266682598 | |
* | |
* ブロック内で標準エラー出力へ出力していたり,入れ子的に使ったりすると, | |
* 表示がおかしなことになってしまうという問題への対策を施したコード | |
* Twitter: http://twitter.com/qnighy/status/9423778596 | |
*/ | |
#include <cstdio> | |
#include <sys/time.h> | |
#include <unistd.h> | |
#include <stdarg.h> | |
using namespace std; | |
struct __bench__ { | |
double start; | |
char msg[100]; | |
__bench__(const char* format, ...) | |
__attribute__((format(printf, 2, 3))) | |
{ | |
va_list args; | |
va_start(args, format); | |
vsnprintf(msg, sizeof(msg), format, args); | |
va_end(args); | |
start = sec(); | |
} | |
~__bench__() { | |
fprintf(stderr, "%s: %.6f sec\n", msg, sec() - start); | |
} | |
double sec() { | |
struct timeval tv; | |
gettimeofday(&tv, NULL); | |
return tv.tv_sec + tv.tv_usec * 1e-6; | |
} | |
operator bool() { return false; } | |
}; | |
#define benchmark(...) if(__bench__ __b__ = __bench__(__VA_ARGS__));else | |
int main() { | |
int i = 1; | |
int j = 3; | |
benchmark("sleep(%d) and %d", i, j) { | |
benchmark("sleep(%d)", j) { | |
sleep(j); | |
} | |
sleep(i); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment