std::vectorでのforeach検証
超適当検証なので結果は保障しません。
逆アセンブリをみてみるとunrollはiterator使った場合でもされているようです。ただかなり単純な処理でないとunrollされないので、気にしなくてもいいみたいです。
配列形参照を使ったほうが3倍早い結果になりましたが、原因はよくわかりません。でも実際のプログラムで顕著になるほどの差ではないみたいなので、好きなほうを使えばいいみたいです。
以下適当ソース。
スーパーpre記法をさっそく使ってみる
#include <iostream> #include <vector> #include "windows.h" #include "mmsystem.h" int _tmain(int argc, _TCHAR* argv[]) { timeBeginPeriod(1); std::vector<int> test(1000000); // init random (to avoid optimization) { std::vector<int>::iterator i, iEnd = test.end(); for(i = test.begin(); i != iEnd; ++ i) { *i = rand(); } } int aavg = 0, bavg = 0; const int nTrial = 100; for(int iTrial = 0; iTrial < nTrial; ++iTrial) { DWORD z = timeGetTime(); std::vector<int>::iterator i, iEnd = test.end(); for(i = test.begin(); i != iEnd; ++i) { *i = 0; } DWORD a = timeGetTime(); const int nCount = (int) test.size(); for(int n = 0; n < nCount; ++ n) { test[n] = 0; } DWORD b = timeGetTime(); aavg += a - z; bavg += b - a; } std::cout << "method a average:" << (double)aavg / nTrial << std::endl; std::cout << "method b average:" << (double)bavg / nTrial << std::endl; char c; std::cin >> c; timeEndPeriod(1); return 0; }