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

Sup*_*ing 0 c++ algorithm hash time

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

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

我该如何计时?

谢谢!

Tho*_*ini 5

首先来看看我对这个问题的回答 ; 它包含一个便携式(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;
Run Code Online (Sandbox Code Playgroud)

全部完成!(注意我还没有尝试编译它)