// test.cpp 文件 #include#include #include using namespace std; template R time_code(F func) { auto then = std::chrono::system_clock::now(); for (int i = 0; i < Count; ++i) { func(); } auto now = std::chrono::system_clock::now(); auto dur = now - then; return std::chrono::duration_cast (dur); } template R time_code_once(F func) { return time_code (func); } int main() { constexpr int Count = 10; using ms = std::chrono::microseconds; auto time1 = time_code ([]() { printf("Hello Worldn"); }); std::cerr << "printf("Hello World\n") x 10, Took: " << time1.count() << " xC2xB5s to execute." << std::endl; auto time2 = time_code_once ([]() { printf("Hello Worldn"); }); std::cerr << "printf("Hello World\n") once, Took: " << time2.count() << " xC2xB5s to execute." << std::endl; }
编译以上源码:g++ test.cpp -o main -std=c++11
编译完成以后运行:./main
输出如下:



