![](/img/trans.png)
[英]Why does switching the order of for loops significantly change the execution time?
[英]Comparing algorithms' execution time: why does the order of execution matter?
每當我嘗試比較兩個競爭算法的執行時間(使用C ++)時,我就像以前在這個問題中建議的那樣使用std::chrono
: 測量C ++中函數的執行時間
但是,我始終注意到所比較的算法的執行順序會顯着影響執行時間。 它甚至經常改變哪種競爭算法被認為是最快的。 例如,假設我有兩個算法algo1
和algo2
。
我的意思是下面的代碼:
std::chrono::high_resolution_clock::time_point start0, start1;
std::chrono::high_resolution_clock::time_point end0, end1;
start1 = std::chrono::high_resolution_clock::now();
algo1();
end1 = std::chrono::high_resolution_clock::now();
start2 = std::chrono::high_resolution_clock::now();
algo2();
end2 = std::chrono::high_resolution_clock::now();
auto time_elapsed1 = std::chrono::duration_cast<std::chrono::nanoseconds>(end1 - start1).count();
auto time_elapsed2 = std::chrono::duration_cast<std::chrono::nanoseconds>(end2 - start2).count();
從以下代碼中得到不同的結果:
std::chrono::high_resolution_clock::time_point start0, start1;
std::chrono::high_resolution_clock::time_point end0, end1;
start2 = std::chrono::high_resolution_clock::now();
algo2();
end2 = std::chrono::high_resolution_clock::now();
start1 = std::chrono::high_resolution_clock::now();
algo1();
end1 = std::chrono::high_resolution_clock::now();
auto time_elapsed1 = std::chrono::duration_cast<std::chrono::nanoseconds>(end1 - start1).count();
auto time_elapsed2 = std::chrono::duration_cast<std::chrono::nanoseconds>(end2 - start2).count();
對於我可能想要比較的幾乎所有算法1和2而言。
所以,我的問題是雙重的:1)為什么會這樣,即為什么訂單很重要? 2)是否有更好的方法來比較兩種算法的執行時間,即如何進行更好和更准確的比較?
PS:當然,我總是測試所有編譯器的優化。
這很可能是由於緩存造成的。
您可以通過多次運行SAME算法輕松驗證緩存的效果。 您可能會注意到,第一次執行所花費的時間比后續執行時間長得多。
當我不得不為我的博士論文比較兩種算法時,我最終連續10次執行每個算法,丟棄第一個結果,然后平均剩余的9個結果,這9個結果非常一致。
可以說是丟棄的第一個結果是否重要,但對我來說卻不是,因為我更感興趣的是比較兩種算法的相對性能(因此尋找每種算法的一致運行時間)而不是而不是測量緩存的影響或每種算法在不同情況下的絕對性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.