I'm quiet experienced in programming, but new to C++. I'm trying to measure the time it takes to run a code. In the future I might write code that can take hours/days to finish itself. Therefore it is important for me to know the limits of the chrono time measurement. Accuracy in milliseconds should be sufficient.
What is the maximum time I can measure?
I have used the following code, please let me know if this can be improved:
#include <chrono>
using namespace std::chrono;
auto start = high_resolution_clock::now();
// calculations here
auto finish = high_resolution_clock::now();
duration<double> elapsed = finish - start; // elapsed time in seconds
cout << elapsed.count();
Here's an informative little HelloWorld:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
using namespace std;
using years = duration<double, ratio_multiply<ratio<86'400>, ratio<146'097, 400>>>;
cout << years{high_resolution_clock::time_point::max() -
high_resolution_clock::now()}.count()
<< " years until overflow\n";
}
I first create a double-based years duration so that the output is easy to read. Then I subtract now() from the time_point's max(), convert that to years and print it out.
For me this just output:
292.256 years until overflow
std::chrono::milliseconds is guaranteed to be stored on a underlying signed integer of at least 45 bits which means that if your elapsed duration is less than 544 years you should be fine.
Source: https://en.cppreference.com/w/cpp/chrono/duration
Edit: As orlp pointed out you might have some issues if/when the clock overflow (but I do not see any mention of it on cppreference).
Also,
The high_resolution_clock is not implemented consistently across different standard library implementations, and its use should be avoided.
[...]
Generally one should just use std::chrono::steady_clock or std::chrono::system_clock directly instead of std::chrono::high_resolution_clock: use steady_clock for duration measurements, and system_clock for wall-clock time.
The C `clock()` function just returns a zero
clock() function always returning 0
why C clock() returns 0
I looked up all these questions and answers
And I learned that clock() returns clock ticks per some constant which differs per systems
And time() returns the number of seconds.
First, I was trying to measure the execution time of my sorting algorithm using clock() like this:
#include <iostream>
#include <ctime>
... Some other headers and codes
a = clock();
exchange_sort();
a = clock() - a;
... Rest of the code
I tried many different data types with a like int, clock_t, long, float.
And I sorted a pretty big size array int arr[1000] with already increased order.
But the value of a was always 0, so I tried to find the reason using gdb and I set a breakpoint to the line where the sorting algorithm is located so that I can check the value of a = clock(); and there has to be some number inside the variable but there was only 0.
So after that, I tried to check whether the function was the problem itself or something else like this:
#include <iostream>
#include <iostream>
int main()
{
int a;
clock_t b;
float c;
long d;
a = clock();
b = clock();
c = clock();
d = clock();
return 0;
}
And I checked the value of each variable through gdb and there were just garbage numbers before I put the return value of clock() but after I put there were only 0s inside the variables.
So apparently clock() just returns 0 all the time in my conclusion
I really don't know how can I fix this
My g++ version is 4.4.7.
I ran this in Linux
My processor is x86_64-redhat-linux
The clock() function is a coarse measure of CPU time used. Your code doesn't use enough CPU time to measure with such a coarse measure. You should probably switch to something like getrusage instead.
My code used enough CPU time. But it seems the clock is only ticking with a step of 15625ms.
My advice is to use <chrono> instead.
Given a while loop and the function ordering as follows:
int k=0;
int total=100;
while(k<total){
doSomething();
if(approx. t milliseconds elapsed) { measure(); }
++k;
}
I want to perform 'measure' every t-th milliseconds. However, since 'doSomething' can be close to the t-th millisecond from the last execution, it is acceptable to perform the measure after approximately t milliseconds elapsed from the last measure.
My question is: how could this be achieved?
One solution would be to set timer to zero, and measure it after every 'doSomething'. When it is withing the acceptable range, I perform measures, and reset. However, I'm not which c++ function I should use for such a task. As I can see, there are certain functions, but the debate on which one is the most appropriate is outside of my understanding. Note that some of the functions actually take into account the time taken by some other processes, but I want my timer to only measure the time of the execution of my c++ code (I hope that is clear). Another thing is the resolution of the measurements, as pointed out below. Suppose the medium option of those suggested.
High resolution timing is platform specific, and you have not specified in the question. The standard library clock() function returns a count that increments at CLOCKS_PER_SEC per second. On some platforms this may be fast enough to give you the resolution you need but you should check your system's tick rate since it is implementation defined. However if you find it is high enough then:
#define SAMPLE_PERIOD_MS 100
#define SAMPLE_PERIOD_TICKS ((CLOCKS_PER_SEC * SAMPLE_PERIOD_MS) / 1000)
int k=0;
int total=100;
clock_t measure_time = clock() + SAMPLE_PERIOD_TICKS ;
while(k<total)
{
doSomething();
if( clock() - measure_time > 0 )
{
measure();
measure_time += SAMPLE_PERIOD_TICKS ;
++k;
}
}
You might replace clock() with some other high-resolution clock source if necessary.
However note a couple of issues. This method is a "busy-loop"; unless either doSomething() or measure() yield the CPU, the process will take all the cpu cycles it can. If this is the only code running on a target, that may not matter. On the other hand is this is running on a general purpose OS such as Windows or Linux which are not real-time, the process may be pre-empted by other processes, and this may affect the accuracy of the sampling periodicity. If you need accurate timing use of an RTOS and performing doSomething() and measure() in separate threads would be better. Even in a GPOS that would be better. For example a general pattern (using a made-up API in teh absence of any specification) would be:
int main()
{
StartThread( measure_thread, HIGH_PRIORITY ) ;
for(;;)
{
doSomething() ;
}
}
void measure_thread()
{
for(;;)
{
measure() ;
sleep( SAMPLE_PERIOD_MS ) ;
}
}
The code for measure_thread() is only accurate if measure() takes a negligible time to run. If it takes significant time you may need to account for that. If it is non-deterministic, you may even have to measure its execution time in order to subtract it the sleep period.
Am I doing it correctly? At times, my program will print 2000+ for the chrono solution and it always prints 1000 for the CLOCKS_PER_SEC..
What is that value I'm actually calculating? Is it Clocks Per Sec?
#include <iostream>
#include <chrono>
#include <thread>
#include <ctime>
std::chrono::time_point<std::chrono::high_resolution_clock> SystemTime()
{
return std::chrono::high_resolution_clock::now();
}
std::uint32_t TimeDuration(std::chrono::time_point<std::chrono::high_resolution_clock> Time)
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(SystemTime() - Time).count();
}
int main()
{
auto Begin = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::cout<< (TimeDuration(Begin) / 1000.0)<<std::endl;
std::cout<<CLOCKS_PER_SEC;
return 0;
}
In order to get the correct ticks per second on Linux, you need to use the return value of ::sysconf(_SC_CLK_TCK) (declared in the header unistd.h), rather than the macro CLOCKS_PER_SEC.
The latter is a constant defined in the POSIX standard – it is unrelated to the actual ticks per second of your CPU clock. For example, see the man page for clock:
C89, C99, POSIX.1-2001. POSIX requires that CLOCKS_PER_SEC equals 1000000 independent of the actual resolution.
However, note that even when using the correct ticks-per-second constant, you still won't get the number of actual CPU cycles per second. "Clock tick" is a special unit used by the CPU clock. There is no standardized definition of how it relates to actual CPU cycles.
In boost's library, there is a timer class, use CLOCKS_PER_SEC to calculate the maximum time the timer can elapse. It said that on Windows CLOCKS_PER_SEC is 1000 and on Mac OS X, Linux it is 1000000. So on the latter OSs, the accuracy is higher.
I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at?
I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attempt to implement this.
An updated answer for C++11:
Use the sleep_for and sleep_until functions:
#include <chrono>
#include <thread>
int main() {
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono; // nanoseconds, system_clock, seconds
sleep_for(nanoseconds(10));
sleep_until(system_clock::now() + seconds(1));
}
With these functions there's no longer a need to continually add new functions for better resolution: sleep, usleep, nanosleep, etc. sleep_for and sleep_until are template functions that can accept values of any resolution via chrono types; hours, seconds, femtoseconds, etc.
In C++14 you can further simplify the code with the literal suffixes for nanoseconds and seconds:
#include <chrono>
#include <thread>
int main() {
using namespace std::this_thread; // sleep_for, sleep_until
using namespace std::chrono_literals; // ns, us, ms, s, h, etc.
using std::chrono::system_clock;
sleep_for(10ns);
sleep_until(system_clock::now() + 1s);
}
Note that the actual duration of a sleep depends on the implementation: You can ask to sleep for 10 nanoseconds, but an implementation might end up sleeping for a millisecond instead, if that's the shortest it can do.
In Win32:
#include<windows.h>
Sleep(milliseconds);
In Unix:
#include<unistd.h>
unsigned int microsecond = 1000000;
usleep(3 * microsecond);//sleeps for 3 second
sleep() only takes a number of seconds which is often too long.
#include <unistd.h>
usleep(3000000);
This will also sleep for three seconds. You can refine the numbers a little more though.
Do you want something as simple like:
#include <unistd.h>
sleep(3);//sleeps for 3 second
Note that this does not guarantee that the amount of time the thread sleeps will be anywhere close to the sleep period, it only guarantees that the amount of time before the thread continues execution will be at least the desired amount. The actual delay will vary depending on circumstances (especially load on the machine in question) and may be orders of magnitude higher than the desired sleep time.
Also, you don't list why you need to sleep but you should generally avoid using delays as a method of synchronization.
You can try this code snippet:
#include<chrono>
#include<thread>
int main(){
std::this_thread::sleep_for(std::chrono::nanoseconds(10));
std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::seconds(1));
}
You can also use select(2) if you want microsecond precision (this works on platform that don't have usleep(3))
The following code will wait for 1.5 second:
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>`
int main() {
struct timeval t;
t.tv_sec = 1;
t.tv_usec = 500000;
select(0, NULL, NULL, NULL, &t);
}
`
I found that "_sleep(milliseconds);" (without the quotes) works well for Win32 if you include the chrono library
E.g:
#include <chrono>
using namespace std;
main
{
cout << "text" << endl;
_sleep(10000); // pauses for 10 seconds
}
Make sure you include the underscore before sleep.
Yes, sleep is probably the function of choice here. Note that the time passed into the function is the smallest amount of time the calling thread will be inactive. So for example if you call sleep with 5 seconds, you're guaranteed your thread will be sleeping for at least 5 seconds. Could be 6, or 8 or 50, depending on what the OS is doing. (During optimal OS execution, this will be very close to 5.) Another useful feature of the sleep function is to pass in 0. This will force a context switch from your thread.
Some additional information:
http://www.opengroup.org/onlinepubs/000095399/functions/sleep.html
The top answer here seems to be an OS dependent answer; for a more portable solution you can write up a quick sleep function using the ctime header file (although this may be a poor implementation on my part).
#include <iostream>
#include <ctime>
using namespace std;
void sleep(float seconds){
clock_t startClock = clock();
float secondsAhead = seconds * CLOCKS_PER_SEC;
// do nothing until the elapsed time has passed.
while(clock() < startClock+secondsAhead);
return;
}
int main(){
cout << "Next string coming up in one second!" << endl;
sleep(1.0);
cout << "Hey, what did I miss?" << endl;
return 0;
}
to delay output in cpp for fixed time, you can use the Sleep() function by including windows.h header file
syntax for Sleep() function is Sleep(time_in_ms)
as
cout<<"Apple\n";
Sleep(3000);
cout<<"Mango";
OUTPUT. above code will print Apple and wait for 3 seconds before printing Mango.
Syntax:
void sleep(unsigned seconds);
sleep() suspends execution for an interval (seconds).
With a call to sleep, the current program is suspended from execution for the number of seconds specified by the argument seconds. The interval is accurate only to the nearest hundredth of a second or to the accuracy of the operating system clock, whichever is less accurate.
Many others have provided good info for sleeping. I agree with Wedge that a sleep seldom the most appropriate solution.
If you are sleeping as you wait for something, then you are better off actually waiting for that thing/event. Look at Condition Variables for this.
I don't know what OS you are trying to do this on, but for threading and synchronisation you could look to the Boost Threading libraries (Boost Condition Varriable).
Moving now to the other extreme if you are trying to wait for exceptionally short periods then there are a couple of hack style options. If you are working on some sort of embedded platform where a 'sleep' is not implemented then you can try a simple loop (for/while etc) with an empty body (be careful the compiler does not optimise it away). Of course the wait time is dependant on the specific hardware in this case.
For really short 'waits' you can try an assembly "nop". I highly doubt these are what you are after but without knowing why you need to wait it's hard to be more specific.
On Windows you can include the windows library and use "Sleep(0);" to sleep the program. It takes a value that represents milliseconds.