I want to perform the above mentioned operation in Milliseconds as the unit. Which library and function call should I prefer ?
Ty.
Or if you are using Visual Studio 2010 (or another c++0x aware compiler) use
#include <thread>
#include <chrono>
std::this_thread::sleep();
// or
std::this_thread::sleep_for(std::chrono::milliseconds(10));
With older compilers you can have the same convenience using the relevant Boost Libraries
Needless to say the major benefit here is portability and the ease of converting the delay parameter to 'human' units.
You could use the Sleep function from Win32 API.
the windows task scheduler has a granularity far above 1ms (generally, 20ms). you can test this by using the performance counter to measure the time really spent in the Sleep() function. (using QueryPerformanceFrequency() and QueryPerformanceCounter() allows you to measure time down to the nanosecond). note that Sleep(0) makes the thread sleep for the shortest period of time possible.
however, you can change this behavior by using timeBeginPeriod(), and passing a 1ms period. now Sleep(0) should return much faster.
note that this function call was made for playing multimedia streams with a better accuracy. i have never had any problem using this, but the need for such a fast period is quite rare. depending on what you are trying to achieve, there may be better ways to get the accuracy you want, without resorting to this "hack".
Er, the sleep() function from win32 api?
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298%28v=vs.85%29.aspx
Related
Is there some specific number of iterations, that I could make using a for loop, so that it exactly takes 1 second for the loop to be executed completely? For example the following code took 0.125s on my machine to execute:
#include <iostream>
#include <cmath>
using namespace std;
int main(){
long long a=0;
for (a=0;a<=pow(10,4);a++);
}
Though, a <= 8*pow(10,4) took 0.206 s. Compiler is GCC 4.9.2. IDE is codeblocks.
My PC's Specs: OS: Windows 8.1
I am posting this answer to your question, as per the comments received.
It is not possible to make a timer because:
The time that an iteration will take is unpredictable, this depends not only on the CPU used, but you need to take into account power management, the scheduler. (By tux3)
one would have to use a real time OS to accomplish that. There's too much jitter in non realtime OSs. Windows could decide to schedule other processes for a while, or use the CPU for e.g. kernel networking, disk I/O etc. that preempts the timing. (By nos)
One can't "make own timer" in a hosted environment just in standard C++. A timer is essentially a mechanism to communicate with the OS scheduler, and one needs platform-specific OS services for that. (By Kerrek SB)
The compiler would optimize such a loop and will remove it through dead-code elimination (By πάντα ῥεῖ and Jongware).
For a bit of context, I am writing a simple CPU emulator. The emulator process boils down to calling a 'step' function to read and execute the next operation in the program. Currently this is just done as fast as possible in a while loop.
I would like the code to be cross-platform but (unfortunately) windows is the primary target.
I need to be able to execute my Emulator->step() function at regular intervals in the range of 1,000Hz to 100,000Hz.
For a slower loop I would simply use sleep() but (on windows at least) it doesn't have the resolution for such a high frequency.
I have also toyed with spinning a loop checking a Boost microsecond timer. Ignoring the inaccuracy of this method, it uses up real CPU time whilst it is meant to be 'idle'. I am running several emulated CPUs concurrently in threads so the while loop causes a noticeable impact on performance.
Surely there is a method of doing what I want to do with C++?
You can't sleep precisly under Windows (maybe the Windows Performance counter functions help, see Is there a Windows equivalent of nanosleep?).
You said that you run many simulated CPU's concurrently in threads, so one possible solution is to throw the threads away and do the Schedueling for the different CPU's yourself (round robin).
You don't need any special sleep resolution. At the end of each loop, just compute whether you need to sleep or not. If not, run the next loop. If so, sleep for the calculated amount. It won't matter if you sleep a little extra on one loop because this logic will make you sleep less on the next loop.
If you are using a C++11 compiler, have a look at <chrono>. There you can find high precision timers. But be aware, that in a windows environment, these still have low accuracy, which Microsoft will hopefully fix in the next release.
Here's what I'd need to do:
double now=getdoubletimestampsomehow();
Where getdoubletimestampsomehow() should be a straight-forward, easy to use function returning a double value representing the number of seconds elapsed from a given date. I'd need it to be quite precise, but I don't really need it to be more precise than a few milliseconds. Portability is quite important, if it isn't possible to directly port it anywhere could you please tell me both an unix and a windows way to do it?
Have you looked at Boost and particularly its Date_Time library ? Here is the seconds since epoch example.
You will be hard-pressed to find something more portable, and of higher resolution.
Portable good precision double timestamp in C++?
There is no portable way to get high-precision timestamp (milliseconds) without using 3rd party libraries. Maximum precision you'll get is 1 second, using time/localtime/gmtime.
If you're fine with 3rd party libraries, use either Boost or Qt 4.
both an unix and a windows way to do it?
GetSystemTime on Windows and gettimeofday on linux.
Please note that if you're planning to use timestamps to determine order of some events, then it might be a bad idea. System clock might have very limited precision (10 milliseconds on windows platform), in which case several operations performed consequently can produce same timestamp. So, to determine order of events you would need "logical timestamps" ("vector clock" is one of examples).
On windows platform, there are highly precise functions that can be used to determine how much time has passed since some point in the past (QueryPerformanceCounter), but they aren't connected to timestamps.
C++11 introduced the <chrono> header containing quite a few portable clocks. The highest resolution clock among them is the std::chrono::high_resolution_clock.
It provides the current time as a std::chrono::time_point object which has a time_since_epoch member. This might contain what you want.
Reference:
Prior to the release of the C++11 standard, there was no standard way in which one could accurately measure the execution time of a piece of code. The programmer was forced to use external libraries like Boost, or routines provided by each operating system.
The C++11 chrono header file provides three standard clocks that could be used for timing one’s code:
system_clock - this is the real-time clock used by the system;
high_resolution_clock - this is a clock with the shortest tick period possible on the current system;
steady_clock - this is a monotonic clock that is guaranteed to never be adjusted.
If you want to measure the time taken by a certain piece of code for execution, you should generally use the steady_clock, which is a monotonic clock that is never adjusted by the system. The other two clocks provided by the chrono header can be occasionally adjusted, so the difference between two consecutive time moments, t0 < t1, is not always positive.
Doubles are not precise - therefore you idea for double now=getdoubletimestampsomehow(); falls down at the first hurdle.
Others have mentioned other possibilities. I would explore those.
The clock_t implications in time.h released with Turbo C++ v1.01 are good only up to 0.0545XX seconds, meaning any timing I want to do with higher precision is impossible with that library.
I was wondering if anyone knew a good library or method available to elder TurboC++ that I could use instead of time.h calls for better precision?
Is this the ancient Turbo C++ for DOS? I recognise that number as the ~1/18th of a second of the default DOS performance timer.
You can speed up the timer, but you'll have to write an interrupt routine that intercepts that timer and only passes on some of the interrupts. Or you'll get strange behavior from other parts of DOS. I have code for this somewhere which I may be able to dig out.
Use Windows QueryPerformanceCounter (and QueryPerformanceFrequency).
I am curious if there is a build-in function in C++ for measuring the execution time?
I am using Windows at the moment. In Linux it's pretty easy...
The best way on Windows, as far as I know, is to use QueryPerformanceCounter and QueryPerformanceFrequency.
QueryPerformanceCounter(LARGE_INTEGER*) places the performance counter's value into the LARGE_INTEGER passed.
QueryPerformanceFrequency(LARGE_INTEGER*) places the frequency the performance counter is incremented into the LARGE_INTEGER passed.
You can then find the execution time by recording the counter as execution starts, and then recording the counter when execution finishes. Subtract the start from the end to get the counter's change, then divide by the frequency to get the time in seconds.
LARGE_INTEGER start, finish, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&start);
// Do something
QueryPerformanceCounter(&finish);
std::cout << "Execution took "
<< ((finish.QuadPart - start.QuadPart) / (double)freq.QuadPart) << std::endl;
It's pretty easy under Windows too - in fact it's the same function on both std::clock, defined in <ctime>
You can use the Windows API Function GetTickCount() and compare the values at start and end. Resolution is in the 16 ms ballpark. If for some reason you need more fine-grained timings, you'll need to look at QueryPerformanceCounter.
C++ has no built-in functions for high-granularity measuring code execution time, you have to resort to platform-specific code. For Windows try QueryPerformanceCounter: http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx
The functions you should use depend on the resolution of timer you need. Some of them give 10ms resolutions. Those functions are easier to use. Others require more work, but give much higher resolution (and might cause you some headaches in some environments. Your dev machine might work fine, though).
http://www.geisswerks.com/ryan/FAQS/timing.html
This articles mentions:
timeGetTime
RDTSC (a processor feature, not an OS feature)
QueryPerformanceCounter
C++ works on many platforms. Why not use something that also works on many platforms, such as the Boost libraries.
Look at the documentation for the Boost Timer Library
I believe that it is a header-only library, which means that it is simple to setup and use...