【发布时间】:2013-12-12 18:23:54
【问题描述】:
我很好奇for(;;) 和for(:) 之间的区别,
尤其是两者之间的速度。因此,我通过一个包含 1000 万个整数的向量并将它们全部加到一个 for 中进行了一个小测试。我发现for(:) 慢了 1.3。
什么会导致for(:) 这么慢!?
编辑: 似乎 for(:) 使用了向量的迭代器 不像 for(;;) 让它更长。
/Yu"stdafx.h" /GS /analyze- /W3 /Zc:wchar_t /ZI /Gm /Od /sdl /Fd"Debug\vc120.pdb" /fp:precise /D"WIN32" /D" _DEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /RTC1 /Gd /Oy- /MDd /Fa"Debug\" /EHsc /nologo /Fo"Debug\" /Fp"Debug\forvsForLoop.pch"
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <chrono>
void init(std::vector<int> &array){
srand(20);
for (int x = 0; x < 10000000; x++)
array.push_back(rand());
return;
}
unsigned long testForLoop(std::vector<int> &array){
unsigned long result = 0;
for (int x = 0; x < array.size(); x++)
result += array[x];
return result;
}
unsigned long testFor(std::vector<int> &array){
unsigned long result = 0;
for (const int &element : array)
result += element;
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> testingArray;
init(testingArray);
//Warm up
std::cout << "warming up \n";
testForLoop(testingArray);
testFor(testingArray);
testForLoop(testingArray);
testFor(testingArray);
testForLoop(testingArray);
testFor(testingArray);
std::cout << "starting \n";
auto start = std::chrono::high_resolution_clock::now();
testForLoop(testingArray);
auto end = std::chrono::high_resolution_clock::now();
std::cout << "ForLoop took: " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl;
start = std::chrono::high_resolution_clock::now();
testFor(testingArray);
end = std::chrono::high_resolution_clock::now();
std::cout << "For---- took: " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl;
system("pause");
return 0;
}
【问题讨论】:
-
除了提交代码之外,请确保您的基准测试在优化的情况下运行。
-
是的,基于范围的 for 循环使用迭代器,就像您可以使用非基于范围的 for 循环一样。参见例如this reference 用于典型实现。如果您不在其他 for 循环中使用迭代器,则测试不相等。
-
您正在对未优化的代码进行基准测试(
/Od、/D_DEBUG等)。这就像通过衡量谁最能阅读地图来确定跑得最快的人一样。开启优化并重试。 -
优化循环,并且都需要 0 纳秒才能完成。
-
我使用函数的返回值给它们一个目的,这样它们就不会被删除,而 for(;;) 采用:for(:) 的 6006000ns 和 8001200ns
标签: c++