I'm working on a C++ application that needs detailed timing information, down to the millisecond level.
We intend to gather the time to second accuracy using the standard time()
function in <ctime>
. We would like to additionally gather the milliseconds elapsed since the last second given by time()
.
Does anyone know a convenient method for obtaining this information?
As other have said, there is not a portable way to do this.
What I do (On msvc++ and linux/g++) is I use the following class that use QueryPerformanceCounter on Windows and gettimeofday on Linux. It's a timer class that can get you the elapsed time between two calls. You might want to modify it to fits your needs.
GetTickCount in Windows gettimeofday in *nix QueryPerformanceCounter in Windows for better resolution (though GetTickCount should do it)
If you're on Unix, gettimeofday() will return seconds and microseconds, up to the resolution of the system clock.
elapsed will be the elapsed processor time, in seconds.
resolution is operation system dependent, but is generally better than millisecond resolution on most systems.
High Resolution, Low Overhead Timing for Intel Processors
If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained counter you can get for performance measurement.
Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy.
When I run this on my box, I get
Here's the Intel developer's guide that gives tons of detail.
Look into the QueryPerformanceCounter methods if this is for Windows.