Trying to use ctime to calculate the running time of a function - c++

I'm doing an assignment for a CS class, and part of the assignment is using ctime's clock() function to calculate the amount of time a sorting function takes. The code that does this is given to me, but it doesn't seem to work, since the output for elapsedTime is always 0. Here is the given code for this:
const int CLOCKS_PER_MS = CLOCKS_PER_SEC/1000; //clock per milliseconds
...
clock_t Start = clock();
//call sort function here
clock_t End = clock();
int elapsedTime = (End - Start)/CLOCKS_PER_MS; //converts elapsed time from
microseconds to milliseconds.

Related

IBM AIX std::clock()?

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();

Different values in measuring the elapsed time C++

I have a simple code and I used clock() and other suggested methods to measure the running time of program. The problem is I got different values when I run it times to times.
Is there any way to elapsed the real execution time of the program?
Thanks in advance
One way of doint it uses #include <ctime>
clock_t t = clock(); // take a start time
// ... do something
clock_t dt = clock() - t; // take elapsed time
cout << (((double)dt) / CLOCKS_PER_SEC) * 1000); // duration in MILLIseconds.
The other approach uses the high_resolution_clock of #include <chrono>:
chrono::high_resolution_clock::time_point t = chrono::high_resolution_clock::now();
//... do something
chrono::high_resolution_clock::time_point t2 = chrono::high_resolution_clock::now();
cout << chrono::duration_cast<chrono::duration<double>>(t2 - t).count();
// or if you prefer duration_cast<milliseconds>(t2 - t).count();
In any case, it's normal that you find small variations. First reason is your other running programms on your PC. Second reason is the clock accuracy (for example the famous 15 milliseconds on windows).

CTimeSpan always gets zero

I am trying to get the running time of Insertion Sort Algorithm. MSDN said that using CTime could get the Elapsed Time. But I tried many times and always got zero. I thought it is impossible that the time of running this algorithm is zero. There must be some error or something else. Could anybody help me? I posted my code below:
#include <cstdlib>
#include <iostream>
#include <atltime.h>
using namespace std;
//member function
void insertion_sort(int arr[], int length);
int *create_array(int arrSize);
int main() {
//Create random array
int arraySize=100;
int *randomArray=new int[arraySize];
int s;
for (s=0;s<arraySize;s++){
randomArray[s]=(rand()%99)+1;
}
CTime startTime = CTime::GetCurrentTime();
int iter;
for (iter=0;iter<1000;iter++){
insertion_sort(randomArray,arraySize);
}
CTime endTime = CTime::GetCurrentTime();
CTimeSpan elapsedTime = endTime - startTime;
double nTMSeconds = elapsedTime.GetTotalSeconds()*1000;
cout<<nTMSeconds;
return 0;
}//end of main
CTime isn't meant to time things to a resolution less than one second. I think what you are really after is something like GetTickCount or GetTickCount64 . See this MSDN link .
GetTickCount function
Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days.
If using GetTickCount64 you could declare startTime and endTime this way:
uint64_t endTime, startTime, diffTime;
Then use GetTickCount64 to retrieve the time in milliseconds with something like
startTime = GetTickCount64();
... do stuff ...
endTime = GetTickCount64();
diffTime = endTime - startTime;
And of course diffTime can be used however you want.
If you don't need to time things for more than a month then you can simply use GetTickCount and the type returned will be a uint32_t instead of uint64_t
If you need resolution beyond 1 millisecond for timing and your computer supports a high resolution timer then this code may work:
LARGE_INTEGER freq;
double time_sec = 0.0;
if (QueryPerformanceFrequency(&freq))
{
LARGE_INTEGER start;
LARGE_INTEGER stop;
QueryPerformanceCounter(&start);
// Do Stuff to time Here
QueryPerformanceCounter(&stop);
time_sec = (uint64_t)(stop.QuadPart - start.QuadPart) / (double)freq.QuadPart;
}
else {
cout << "Your computer doesn't have a high resolution timer to use";
}
Information on the high performance timer can be found in this MSDN entry

Why the time taken by a thread is more than the total time taken by a process?

I am executing the code to calculate the time taken by a Matrix multiplication Code.
I have created four threads and called the Calculate method like this:
std::thread t1( Calculate );
std::thread t2( Calculate );
std::thread t3( Calculate );
std::thread t4( Calculate );
t1.join();
t2.join();
t3.join();
t4.join();
This is the code where I am doing the matrix multiplication
void calculate()
{
clock_t starttime = clock();
// some Code
clock_t endtime = clock();
cout << "Time Taken:"<<diffclock(endtime, starttime)<<"sec."<<endl;
}
This is the method to calculate time difference:
double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks)/CLOCKS_PER_SEC;
return diffms;
}
After the execution the time taken by whole execution is displayed incorrectly. The time taken by the operation is around 22 seconds but the code is giving nearly 32 seconds as time taken. I have checked it from stopwatch and the output by this code is Incorrect.
As per the documentation of clock
In order to measure the time spent in a program, clock() should be called
at the start of the program and its return value subtracted from the value
returned by subsequent calls. The value returned by clock() is defined for
compatibility across systems that have clocks with different resolutions.
To determine the time in seconds, the value returned by clock() should be
divided by the value of the macro CLOCKS_PER_SEC. CLOCKS_PER_SEC is defined
to be one million in <time.h>.
However the time returned by this time calculating code contradicts with the time provided by the IDE. I am using code::blocks here.
Am I missing some thing?
Since you're on C++11, you can use std::chrono:
std::chrono::time_point<std::chrono :: system_clock> start, end;
start = std::chrono::system_clock::now();
// calculations here...
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed = end-start;
std::cout << "Elapsed time: " << elapsed.count() << "s\n";
Note that you should also use an std::mutex when accessing cout. Your code looks fine, but cout is probably getting mixed up.

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);