Sử dụng thư viện <chrono> (C++11) với high_resolution_clock để đo thời gian thực thi với độ chính xác nanosecond.
Ví dụ mã nguồn
#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;
int main() {
auto start = high_resolution_clock::now();
// Giả lập công việc
for (volatile int i = 0; i < 200000000; i++);
auto end = high_resolution_clock::now();
auto duration = duration_cast<nanoseconds>(end - start).count();
cout << "Thoi gian thuc thi: " << duration << " nanoseconds\n";
cout << "(" << duration/1e6 << " ms)\n";
return 0;
}
Đầu ra mẫu
Thoi gian thuc thi: 536395307 nanoseconds (536.4 ms)
Các đơn vị thời gian thường dùng
nanoseconds- nanogâymicroseconds- microgiâymilliseconds- mili giâyseconds- giây