0

I've been using GetTickCount() from Windows but I've read that it has poor performance/resolution, and I'd like to ask what is the best way to get the time.

I tried using the <ctime> library but it doesn't go for miliseconds or microseconds, and I need something up to that precision.

Thanks!

Danicco
  • 1,573
  • 2
  • 23
  • 49
  • 4
    This is likely answered on Stackoverflow.com already, and this question probably belongs there. – House Jul 20 '13 at 19:30
  • if you are using C++11 you can use std::chrono, otherwise I don't think there is a high precision cross-platform method available. – Ali1S232 Jul 20 '13 at 19:56
  • As a general bit of advice, "cross-platform" is just a short way of saying "constrainted to the least common denominator." Especially in games, you're going to have to come to terms with having per-platform `#ifdef`s here and there. – Sean Middleditch Jul 20 '13 at 19:59

3 Answers3

7

If using C++11, you can use std::chrono::high_resolution_clock

Precision is an implementation detail, e.g it should be implemented as QueryPerformanceCounter on Windows.

#include <chrono>
#include <iostream>

int main(int argc, char *argv[])
{
   auto t1 = std::chrono::high_resolution_clock::now();
   auto t2 = std::chrono::high_resolution_clock::now();
   std::cout << "It took " << std::chrono::nanoseconds(t2 - t1).count() << " nanoseconds" << std::endl;

   return 0;
}
Casper Beyer
  • 2,203
  • 2
  • 22
  • 35
  • 1
    Note that i said _should_ because of the the issue outlined here. https://connect.microsoft.com/VisualStudio/feedback/details/719443/ – Casper Beyer Jul 20 '13 at 20:26
1

If you want cross-platform compatibility, the clock() function from ctime (see docs) is probably your best bet. It's in milliseconds in Visual Studio (although that's no guarantee that it actually advances in 1-millisecond increments), and is presumably similar in other compilers.

Each platform will have its own way of getting higher-resolution timing. On Windows there are timeGetTime() and QueryPerformanceCounter(). You can read about them online; there are tons of articles about each (here's one). If there are other platforms you care about, you'll have to google around or consult their docs for their own high-resolution timing functions.

Nathan Reed
  • 3,583
  • 1
  • 26
  • 33
0

take a look at this, its performance seems better http://www.boost.org/doc/libs/1_38_0/doc/html/date_time.html

Onur A.
  • 3,007
  • 3
  • 22
  • 37