Portable way of counting milliseconds in C++?
Is there any portable (Windows & Linux) way of counting how ma开发者_JAVA百科ny milliseconds elapsed between two calls ?
Basically, I want to achieve the same functionnality than the StopWatch
class of .NET
. (for those who already used it)
In a perfect world, I would have used boost::date_time
but that's not an option here due to some silly rules I'm enforced to respect.
For those who better read code, this is what I'd like to achieve.
Timer timer;
timer.start();
// Some instructions here
timer.stop();
// Print out the elapsed time
std::cout << "Elapsed time: " << timer.milliseconds() << "ms" << std::endl;
So, if there is a portable (set of) function(s) that can help me implement the Timer
class, what is it ? If there is no such function, what Windows & Linux API should I use to achieve this functionnality ? (using #ifdef WINDOWS
-like macros)
Thanks !
On Linux (and generally in POSIX), you can use gettimeofday
function, which returns number of microseconds since the Epoch. On Windows, there is GetTickCount
function, that return number of milliseconds since the system was started.
clock() (in Time.h) returns a value which increases CLOCKS_PER_SEC
every second, commonly 1000.
On Windows, use the High Performance Timer, it's a doddle.
LARGE_INTEGER frequency;
LARGE_INTEGER one;
LARGE_INTEGER two;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&one);
// something
QueryPerformanceCounter(&two);
std::cout << (((double)two.QuadPart - (double)one.QuadPart) / (double)frequency.QuadPart) * (double)1000;
In theory, this can go up to per-clock-cycle accuracy, depending on the CPU in question.
This is my code for this task (Boost license)
Where ptime is class that represents time in seconds + nanoseconds ptime(int sec,int nano)
And ptime::microseconds create sec/nano pair from posix time microseconds.
It is quite easy to rewrite it for your needs and write such class.
ptime ptime::now()
{
#ifndef BOOSTER_WIN_NATIVE
struct timeval tv;
gettimeofday(&tv,0);
return ptime(tv.tv_sec,tv.tv_usec * 1000);
#else
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
unsigned long long tt = ft.dwHighDateTime;
tt <<=32;
tt |= ft.dwLowDateTime;
tt /=10;
tt -= 11644473600000000ULL;
return ptime(ptime::microseconds(tt));
#endif
}
And there is no portable C++ function for this...
精彩评论