LoginSignup
2
2

More than 5 years have passed since last update.

C++11で処理速度を精度よく計測してみる?

Posted at

forとwhileのループ処理に速度差があるのかを知りたくてちょっと書いてみました。

ウンコードの可能性もあるのでもしより良い方法あれば指摘して頂けると助かります。

while ループによる計測

#include <iostream>
#include <chrono>
int main()
{
auto t = 0;
auto n = 0;
while ( 100 > n ){
auto time_point = std::chrono::high_resolution_clock::now() ;
//計測する処理を入れる
auto i = 0;
        while ( i < 10000000 ){
        i = ++i ;
        }
//ここまで
auto duration = std::chrono::high_resolution_clock::now() - time_point;

auto count = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();

std::cout << "処理時間:" << std::chrono::duration_cast<std::chrono::microseconds>(duration).count() << "[μs]" << std::endl;
n = ++n;
t = count + t;
}
t = t / 100;
std::cout << "100回処理平均時間:" << t << "[μs]" << std::endl;
return 0;
}

for ループによる計測


#include <iostream>
#include <chrono>
int main()
{
auto t = 0;
auto n = 0;
while ( 100 > n ){
auto time_point = std::chrono::high_resolution_clock::now() ;
//計測する処理を入れる
auto i = 0;
        for ( ; i < 10000000 ;){
        i = ++i ;
        }
//ここまで
auto duration = std::chrono::high_resolution_clock::now() - time_point;

auto count = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();

std::cout << "処理時間:" << std::chrono::duration_cast<std::chrono::microseconds>(duration).count() << "[μs]" << std::endl;
n = ++n;
t = count + t;
}
t = t / 100;
std::cout << "100回処理平均時間:" << t << "[μs]" << std::endl;
return 0;
}

どちらもインクリメントを10,000,000(1千万)まで行い、それを100回繰り返すコードになってます。その平均値を最後に出力しています。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2