C++ 用 std::chrono 來簡單計時

每次要簡單計時,第一個念頭都會先想說用用 c++ 11 的 chrono library。通常會有 50 % 機率覺得,std::chrono 的 naming prefix 實在是又臭又長,就改用回 win32 的 timeGetTime...

timeGetTime style
auto ts = timeGetTime();
...
/* processing */
...
auto ms = timeGetTime() - ts;
printf("cost in %d\n", ms);
chrono style
auto ts = std::chrono::steady_clock::now();
...
/* processing */
...
auto duration = std::chrono::steady_clock::now() - ts;
auto ms = std::chrono::duration_cast<std::chrono::millieseconds>(duration).count();
print("cost in %d\n", ms);

簡單打包一下

時間戳記
auto make_stamp() { return std::chrono::steady_clock::now(); }
單位 alias
using u_mu = std::chrono::microseconds;
using u_ms = std::chrono::milliseconds;
using u_s = std::chrono::seconds;
實際秒數
template<typename TimeUnit = u_ms>
auto make_dur(decltype(make_stamp()) ts) { return std::chrono::duration_cast<TimeUnit>(std::chrono::steady_clock::now() - ts).count(); }

實際情境

easy chrono style
auto ts = make_stamp();
...
/* processing */
...
auto ms = make_dur<u_ms>(ts);
printf("cost in %d ms\n", ms);

Live

comments powered by Disqus