#include <unistd.h> // for sleep() #include <iostream> #include <chrono> void thingToTime() { sleep(1); } int main() { // In Nanoseconds { auto start = std::chrono::high_resolution_clock::now(); thingToTime(); auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count(); std::cout << duration << " nanoseconds\n"; } // In Milliseconds { auto start = std::chrono::system_clock::now(); thingToTime(); auto end = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); std::cout << duration << " milliseconds\n"; } // In Seconds { auto start = std::chrono::system_clock::now(); thingToTime(); auto end = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(end - start).count(); std::cout << duration << " seconds (C++11)\n"; } // In Seconds classic { time_t start = time(NULL); thingToTime(); time_t end = time(NULL); time_t duration = end - start; std::cout << duration << " seconds (classic)\n"; } }
Programming Tips - C++: Time something in nanoseconds/milliseconds/seconds
Date: 2022jul14
Language: C/C++
Q. C++: Time something in nanoseconds/milliseconds/seconds
A. Use std::chrono which was introduced in C++11.