Three common approaches exist for measuring code execution time in C++: the high-resolution chrono library, the traditional time() function, and the clock() function.
High-Resolution Timing with std::chrono
C++11’s chrono library offers precise measurement of elapsed wall-clock time. A typical pattern is:
#include <chrono>
#include <iostream>
int main() {
auto t1 = std::chrono::steady_clock::now();
// Code block to profile
for (int i = 0; i < 1000000; ++i) { }
auto t2 = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = t2 - t1;
std::cout << "Elapsed: " << elapsed.count() * 1000 << " ms\n";
}
Use std::chrono::steady_clock when you need monotonically increasing time unaffected by system clock adjustments. For UTC-based timestamps, system_clock is more appropriate.
Wall-Clock Seconds with time()
The time() function from <ctime> returns seconds since the Epoch and provides a coarse elapsed time measurement.
#include <ctime>
#include <iostream>
int main() {
time_t begin = time(nullptr);
// Code to measure
for (int i = 0; i < 100000000; ++i) { }
time_t end = time(nullptr);
std::cout << "Wall time: " << difftime(end, begin) << " s\n";
}
This meausres real elapsed time with second-level granularity, suitable for longer running tasks where high precision isn’t critical.
Processor Time with clock()
The clock() function from <ctime> returns the processor time consumed by the program since execution began. It offers higher accuracy than time() for CPU-boundd work.
#include <ctime>
#include <iostream>
int main() {
clock_t start = clock();
// CPU-intensive code
for (volatile int i = 0; i < 10000000; ++i) { }
clock_t finish = clock();
double cpu_time = static_cast<double>(finish - start) / CLOCKS_PER_SEC;
std::cout << "CPU time: " << cpu_time << " s\n";
}
Note that clock() returns CPU time, not real-world time, which can be a better metric for algorithmic benchmarking when the process isn’t preempted.