每当我尝试比较两个竞争算法(使用C++)的执行时间时,我使用
我的意思是下面的代码:
与以下代码产生不同的结果:
std::chrono
,就像在此问题中以前建议的一样:Measuring execution time of a function in 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)有没有更好的比较两个算法在执行时间方面的方法,即应该如何进行更好和更准确的比较?
附注:当然,我总是测试所有编译器的优化。