我正在尝试对一段代码进行基准测试。它基于此代码 here有趣的部分基本上是这样的:
auto t0 = std::chrono::high_resolution_clock::now();
...
auto t1 = std::chrono::high_resolution_clock::now();
std::cout << secs(t1-t0).count() << " s\n";
问题是我在一台共享机器上,这给了我时间,所以我的结果没有给我任何一致的东西。我真正需要的是某种秒表工具,它可以让我只知道代码运行的时间,而不是墙上的时间。有哪些选择?如果涉及系统特定的调用,我在 Linux 机器上,但我宁愿尽可能保持此代码的可移植性。
最佳答案
如果您的操作系统可用,您可以使用 times API获得与内置 time
命令类似的结果。
#include <sys/times.h>
...
struct tms start, end;
times(&start);
//Do command
times(&end);
clock_t usr_time = end->tms_utime - start->tms_utime;
clock_t sys_time = end->tms_stime - start->tms_stime;
要 100% 完成,您应该检查时间的结果是否不等于 -1
,否则检查 errno
代码。
关于c++ - C++ 如何获取一段代码的执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24560962/