[CodeStudy] Using C++ Lib Chrono to record execution time
Using C++ Lib Chrono to record execution time
Chrono is a flexible collection of types that track time with varying degrees of precision.
Here are several methods that can record the execution time.
ctime
#include <ctime>
using namespace std;
clock_t start = clock();
// do something...
clock_t end = clock();
cout << "cost" << (double)(end - start) / CLOCKS_PER_SEC << "s" << endl;
chrono
#include <chrono>
auto start = steady_clock::now();
auto end = steady_clock::now();
auto duration = duration_cast<milliseconds>(end - start);
printf("[INFO] Execution time %ld ms\n", duration.count());
You can change the unit of the time with duration_cast
, including:
- nanoseconds
- microseconds
- milliseconds
- seconds
- minutes
- hours