IBM AIX std::clock()? - c++

I execute in IBM AIX the following code.
int main(void)
{
printf( "start\n");
double time1 = (double)clock(); /* get initial time */
time1 = time1 / CLOCKS_PER_SEC; /* in seconds */
boost::this_thread::sleep_for(boost::chrono::seconds(5));
/* call clock a second time */
double time2 = (((double)clock()) / CLOCKS_PER_SEC);
double timedif = time2 - time1;
printf( "The elapsed time is %lf seconds, time1:%lf time2:%lf CLOCKS_PER_SEC:%ld\n",
timedif));
}
The result is:
2018-04-07 09:58:37 start
2018-04-07 09:58:42 The elapsed time is 0.000180 seconds, time1:0.000000
time2:0.000181 CLOCKS_PER_SEC:1000000
I don't know why elapsed time is 0.000180 (why not 5)?

According to the manual
Returns the processor time consumed by the program.
It is CPU time consumed by a program, it is not a physical time. A sleeping program does not consume CPU time. Thus in raw words, it is time interval from main till sleep plus time interval after sleep till return.
If you want to get system/real time, look at the std::chrono::system_clock class.
#include <chrono>
using std::chrono::system_clock;
system_clock::time_point time_now = system_clock::now();

Related

Difference between clock and high_resolution_clock [duplicate]

I was trying to measure the time taken to execute a specific function in my code. Initially I used the clock() function as below
clock_t start = clock();
do_something();
clock_t end = clock();
printf("Time taken: %f ms\n", ((double) end - start)*1000/CLOCKS_PER_SEC);
Later I was reading about the chrono library in C++11 and tried to measure the same with a std::chrono::steady_clock as below
using namespace std::chrono;
auto start = steady_clock::now();
do_something();
auto end = steady_clock::now();
printf("Time taken: %lld ms\n", duration_cast<milliseconds>(end - start).count());
The time measured by the first code snippet (using clock) was 89.53 ms and that measured by steady_clock was 1140 ms.
Why is there such a big difference in time measured by both the clocks?
clock measures processor time, whereas steady_clock measures physical time. So you can get differences like this if do_something() was preempted by other processes (such as checking mail or whatever).
Daniel H makes a great point below in the comments that this can also happen if do_something() isn't CPU bound. For example if it sleeps, blocks on locking a mutex, waits on a condition variable, etc.

Time a function in C++

I'd like to time how long a function takes in C++ in milliseconds.
Here's what I have:
#include<iostream>
#include<chrono>
using timepoint = std::chrono::steady_clock::time_point;
float elapsed_time[100];
// Run function and count time
for(int k=0;k<100;k++) {
// Start timer
const timepoint clock_start = chrono::system_clock::now();
// Run Function
Recursive_Foo();
// Stop timer
const timepoint clock_stop = chrono::system_clock::now();
// Calculate time in milliseconds
chrono::duration<double,std::milli> timetaken = clock_stop - clock_start;
elapsed_time[k] = timetaken.count();
}
for(int l=0;l<100;l++) {
cout<<"Array: "<<l<<" Time: "<<elapsed_time[l]<<" ms"<<endl;
}
This compiles but I think multithreading is preventing it from working properly. The output produces times in irregular intervals, e.g.:
Array: 0 Time: 0 ms
Array: 1 Time: 0 ms
Array: 2 Time: 15.6 ms
Array: 3 Time: 0 ms
Array: 4 Time: 0 ms
Array: 5 Time: 0 ms
Array: 6 Time: 15.6 ms
Array: 7 Time: 0 ms
Array: 8 Time: 0 ms
Do I need to use some kind of mutex lock? Or is there an easier way to time how many milliseconds a function took to execute?
EDIT
Maybe people are suggesting using high_resolution_clock or steady_clock, but all three produce the same irregular results.
This solution seems to produce real results: How to use QueryPerformanceCounter? but it's not clear to me why. Also, https://gamedev.stackexchange.com/questions/26759/best-way-to-get-elapsed-time-in-miliseconds-in-windows works well. Seems to be a Windows implementation issue.
Microsoft has a nice, clean solution in microseconds, via: MSDN
#include <windows.h>
LONGLONG measure_activity_high_resolution_timing()
{
LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
LARGE_INTEGER Frequency;
QueryPerformanceFrequency(&Frequency);
QueryPerformanceCounter(&StartingTime);
// Activity to be timed
QueryPerformanceCounter(&EndingTime);
ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;
//
// We now have the elapsed number of ticks, along with the
// number of ticks-per-second. We use these values
// to convert to the number of elapsed microseconds.
// To guard against loss-of-precision, we convert
// to microseconds *before* dividing by ticks-per-second.
//
ElapsedMicroseconds.QuadPart *= 1000000;
ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;
return ElapsedMicroseconds.QuadPart;
}
Profile code using a high-resolution timer, not the system-clock; which, as you're seeing, has a very limited granularity.
http://www.cplusplus.com/reference/chrono/high_resolution_clock/
typedef tp high_resolution_clock::time_point
const tp start = high_resolution_clock::now();
// do stuff
const tp end = high_resolution_clock::now();
If you suspect that some other process or thread in your app is taking too much CPU time then use:
GetThreadTimes under windows
or
clock_gettime with CLOCK_THREAD_CPUTIME_ID under linux
to measure threads CPU time your function was being executed. This will exclude from your measurements time other threads/processes were executed during profiling.

precise time measurement

I'm using time.h in C++ to measure the timing of a function.
clock_t t = clock();
someFunction();
printf("\nTime taken: %.4fs\n", (float)(clock() - t)/CLOCKS_PER_SEC);
however, I'm always getting the time taken as 0.0000. clock() and t when printed separately, have the same value. I would like to know if there is way to measure the time precisely (maybe in the order of nanoseconds) in C++ . I'm using VS2010.
C++11 introduced the chrono API, you can use to get nanoseconds :
auto begin = std::chrono::high_resolution_clock::now();
// code to benchmark
auto end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << "ns" << std::endl;
For a more relevant value it is good to run the function several times and compute the average :
auto begin = std::chrono::high_resolution_clock::now();
uint32_t iterations = 10000;
for(uint32_t i = 0; i < iterations; ++i)
{
// code to benchmark
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count();
std::cout << duration << "ns total, average : " << duration / iterations << "ns." << std::endl;
But remember the for loop and assigning begin and end var use some CPU time too.
I usually use the QueryPerformanceCounter function.
example:
LARGE_INTEGER frequency; // ticks per second
LARGE_INTEGER t1, t2; // ticks
double elapsedTime;
// get ticks per second
QueryPerformanceFrequency(&frequency);
// start timer
QueryPerformanceCounter(&t1);
// do something
...
// stop timer
QueryPerformanceCounter(&t2);
// compute and print the elapsed time in millisec
elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
The following text, that i completely agree with, is quoted from Optimizing software in C++ (good reading for any C++ programmer) -
The time measurements may require a very high resolution if time
intervals are short. In Windows, you can use the
GetTickCount or
QueryPerformanceCounter functions for millisecond resolution. A much
higher resolution can be obtained with the time stamp counter in the
CPU, which counts at the CPU clock frequency.
There is a problem that "the clock frequency may vary dynamically and that
measurements are unstable due to interrupts and task switches."
In C or C++ I usually do like below. If it still fails you may consider using rtdsc functions
struct timeval time;
gettimeofday(&time, NULL); // Start Time
long totalTime = (time.tv_sec * 1000) + (time.tv_usec / 1000);
//........ call your functions here
gettimeofday(&time, NULL); //END-TIME
totalTime = (((time.tv_sec * 1000) + (time.tv_usec / 1000)) - totalTime);

Most efficient way to retrieve a timer?

I've never actually worked with timers before but I need one for my current project.
So this might be a silly question: but what's the 'normal' way to retrieve a timer for a game, and is there a better/more efficient way?
Thanks
Since you may want the time elapsed, and it might be so little, you might need to use the clock() function defined in time.h.
Here what I found about it in the MSDN Library:
Calculates the wall-clock time used by the calling process.
clock_t clock( void );
Return Value
The elapsed wall-clock time since the start of the process (elapsed time in seconds times CLOCKS_PER_SEC). If the amount of elapsed time is unavailable, the function returns –1, cast as a clock_t.
Remarks
The clock function tells how much time the calling process has used. A timer tick is approximately equal to 1/CLOCKS_PER_SEC second. In versions of Microsoft C before 6.0, the CLOCKS_PER_SEC constant was called CLK_TCK.
Example:
// crt_clock.c
// This example prompts for how long
// the program is to run and then continuously
// displays the elapsed time for that period.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void sleep( clock_t wait );
int main( void )
{
long i = 6000000L;
clock_t start, finish;
double duration;
// Delay for a specified time.
printf( "Delay for three seconds\n" );
sleep( (clock_t)3 * CLOCKS_PER_SEC );
printf( "Done!\n" );
// Measure the duration of an event.
printf( "Time to do %ld empty loops is ", i );
start = clock();
while( i-- )
;
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%2.1f seconds\n", duration );
}
// Pauses for a specified number of milliseconds.
void sleep( clock_t wait )
{
clock_t goal;
goal = wait + clock();
while( goal > clock() )
;
}
Output
Delay for three seconds
Done!
Time to do 6000000 empty loops is 0.1 seconds
If you want cross-platform and performant time library, use boost::date_time. For timers, just get current time, and substract it from the next reading (they have operators for computing time difference etc, the code is readable).
Current time is read using boost::posix_time::microsecond_clock::universal_time() and stored in the ptime struct. (the posix_ does not refer to that it is available only on POSIX systems; it only indicates that it is modeled after POSIX time concepts).
If you are using C++ on windows you will want to use QueryPerformanceCounter/QueryPerformanceFrequency
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644904(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx
If you are on linux check out clock_gettime(CLOCK_REALTIME)
http://linux.die.net/man/3/clock_gettime
the clock() suggestion is incorrect as it is time used in the process. since there is a loop his function will end up begin correct, but if you block then this will not work.
http://linux.die.net/man/3/clock

Calculating time length between operations in c++

The program is a middleware between a database and application. For each database access I most calculate the time length in milliseconds. The example bellow is using TDateTime from Builder library. I must, as far as possible, only use standard c++ libraries.
AnsiString TimeInMilliseconds(TDateTime t) {
Word Hour, Min, Sec, MSec;
DecodeTime(t, Hour, Min, Sec, MSec);
long ms = MSec + Sec * 1000 + Min * 1000 * 60 + Hour * 1000 * 60 * 60;
return IntToStr(ms);
}
// computing times
TDateTime SelectStart = Now();
sql_manipulation_statement();
TDateTime SelectEnd = Now();
On both Windows and POSIX-compliant systems (Linux, OSX, etc.), you can calculate the time in 1/CLOCKS_PER_SEC (timer ticks) for a call using clock() found in <ctime>. The return value from that call will be the elapsed time since the program started running in milliseconds. Two calls to clock() can then be subtracted from each other to calculate the running time of a given block of code.
So for example:
#include <ctime>
#include <cstdio>
clock_t time_a = clock();
//...run block of code
clock_t time_b = clock();
if (time_a == ((clock_t)-1) || time_b == ((clock_t)-1))
{
perror("Unable to calculate elapsed time");
}
else
{
unsigned int total_time_ticks = (unsigned int)(time_b - time_a);
}
Edit: You are not going to be able to directly compare the timings from a POSIX-compliant platform to a Windows platform because on Windows clock() measures the the wall-clock time, where-as on a POSIX system, it measures elapsed CPU time. But it is a function in a standard C++ library, and for comparing performance between different blocks of code on the same platform, should fit your needs.
On windows you can use GetTickCount (MSDN) Which will give the number of milliseconds that have elapsed since the system was started. Using this before and after the call you get the amount of milliseconds the call took.
DWORD start = GetTickCount();
//Do your stuff
DWORD end = GetTickCount();
cout << "the call took " << (end - start) << " ms";
Edit:
As Jason mentioned, Clock(); would be better because it is not related to Windows only.