What techniques / methods exist for getting sub-millisecond precision timing data in C or C++, and what precision and accuracy do they provide? I\'m looking for methods tha
Good luck trying to do that with MS Windows. You need a realtime operating system, that is to say, one where timing is guaranteed repeatable. Windows can switch to another thread or even another process at an inopportune moment. You will also have no control over cache misses.
When I was doing realtime robotic control, I used a very lightweight OS called OnTime RTOS32, which has a partial Windows API emulation layer. I do not know if it would be suitable for what you are doing. However, with Windows, you will probably never be able to prove that it will never fail to give the timely response.
When dealing with off-the-shelf operating systems, accurate timing is an extremely difficult and involved task. If you really need guaranteed timing, the only real option is a full real-time operating system. However if "almost always" is good enough, here are a few tricks you can use that will provide good accuracy under commodity Windows & Linux
It seems like a simple question, but attaining 'good' timing get's exponentially more difficult the tighter your timing constraints are. Good luck!
A combination of GetSystemTimeAsFileTime
and QueryPerformanceCounter
can result in a reliable suite of code to obtain microsecond resolution time services on windows.
See this comment in another thread here.
boost::datetime has microsecond precision clock but its accuracy depends on the platform.
The documentation states:
ptime microsec_clock::local_time() "Get the local time using a sub second resolution clock. On Unix systems this is implemented using GetTimeOfDay. On most Win32 platforms it is implemented using ftime. Win32 systems often do not achieve microsecond resolution via this API. If higher resolution is critical to your application test your platform to see the achieved resolution."
http://www.boost.org/doc/libs/1_43_0/doc/html/date_time/posix_time.html#date_time.posix_time.ptime_class
You could try the technique described here, but it's not portable.
Most modern processors have registers for timing or other instrumentation purposes. On x86 since Pentium days there is the RDTSC
instruction, for example. You compiler may give you access to this instruction.
See wikipedia for more info.