C++/C言語の実行時間計測
したい。
関数によってミリ秒だったり秒だったり、OSによって実時間だったりCPU時間だったりする点に注意。
#include <iostream> #include <vector> #include <chrono> #include <time.h> int main() { const int size = 1000 * 1000; //C++11版, ミリ秒単位、実時間ベース std::vector<int> x; auto chrono_start = std::chrono::system_clock::now(); for (int i = 0; i < size; ++i) {x.push_back(i);} auto chrono_end = std::chrono::system_clock::now(); std::cout << "Elapsed time(C++):" << std::chrono::duration_cast<std::chrono::milliseconds>(chrono_end - chrono_start).count() << "[ms]" << std::endl; //C版(1), CLOCKS_PER_SEC 分の1秒単位、実行時間ベース std::vector<int> y; clock_t clock_start = clock(); for (int i = 0; i < size; ++i) { y.push_back(i); } std::cout << "Elapsed time(C-1):" << 1000.0*static_cast<double>(clock()- clock_start) / CLOCKS_PER_SEC << "[ms]" << std::endl; //C版(2), 秒単位 time_t time_start, time_end; time(&time_start); for (int i = 0; i < size; ++i) { y.push_back(i); } time(&time_end); std::cout << "Elapsed time(C-2):" << 1000*difftime(time_end, time_start) << "[ms]" << std::endl; return 0; }
実行結果
>||cpp|
Elapsed time(C++):1241[ms]
Elapsed time(C-1):1207[ms]
Elapsed time(C-2):1000[ms]
|