小编典典

如何知道计算c ++中算法的执行时间?

algorithm

我想通过查看算法的运行时性能来测试哪种数据结构是最佳的,我该怎么做?

例如我已经有一个hashmap<string, int> hmp;
假设我有"apple"我的hashmap,我想知道下面的语句需要多长时间来执行:hmp["apple"]

我该如何计时?

谢谢!


阅读 472

收藏
2020-07-28

共1个答案

小编典典

首先看一下我对这个问题的回答;它包含一个可移植的(windows/linux)函数,以毫秒为单位获取时间。

接下来,执行以下操作:

int64 start_time = GetTimeMs64();
const int NUM_TIMES = 100000; /* Choose this so it takes at the very least half a minute to run */

for (int i = 0; i < NUM_TIMES; ++i) {
   /* Code you want to time.. */
}

double milliseconds = (GetTimeMs64() - start_time) / (double)NUM_TIMES;

全做完了!(请注意,我没有尝试编译它)

2020-07-28