Measuring Time Elapsed in C++ for Accurate Time Tracking

  • Context: C/C++ 
  • Thread starter Thread starter ACLerok
  • Start date Start date
  • Tags Tags
    C++ Measuring Time
Click For Summary

Discussion Overview

The discussion revolves around measuring the elapsed time for function execution in C++ using various timing functions and methods. Participants explore different approaches, code snippets, and the limitations of the timing mechanisms available in C++.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant shares a code snippet using clock() to measure time but finds that it always reports 0 ms, questioning the accuracy of the method.
  • Another participant suggests that averaging the time over multiple executions may yield more reliable results, especially for quick operations.
  • A different code example is provided that correctly uses clock() with a multiplication factor of 1000 for milliseconds, noting that the resolution of clock() is about 15 ms.
  • Concerns are raised about the resolution and accuracy of clock(), with one participant mentioning alternatives like QueryPerformanceCounter() and GetProcessTimes() for higher precision.
  • Another participant points out that clock() measures CPU time rather than wall-clock time, suggesting that I/O operations may affect the reported time.
  • A suggestion is made to use gettimeofday() or other non-standard timing functions for wall-clock time measurement.
  • One participant introduces difftime() from the C/C++ standard library as a simpler alternative for measuring time in seconds, providing an example code snippet.
  • Additional code is shared for converting floating-point numbers to strings, which may be useful for displaying elapsed time.

Areas of Agreement / Disagreement

Participants express differing views on the best method for measuring elapsed time, with no consensus on a single approach. Some favor using clock(), while others advocate for alternatives like difftime() or higher-resolution timers.

Contextual Notes

Limitations include the resolution of clock() being approximately 15 ms, potential overhead from I/O operations affecting timing accuracy, and the need for careful consideration of which timing functions to use based on the desired precision.

Who May Find This Useful

Programmers and developers interested in accurate time measurement in C++ applications, particularly those working on performance analysis or timing-sensitive tasks.

ACLerok
Messages
194
Reaction score
0
I am writing a program and I need to measure the time it takes for a particular function to execute. Here is the code I am using to get familiar with time.h

Code:
#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;


double diffclock(clock_t clock1,clock_t clock2)
{
	double diffticks=clock1-clock2;
	double diffms=(diffticks*10)/CLOCKS_PER_SEC;
	return diffms;
}

int main()
{
	string name;
	int i;
	clock_t begin=clock();
	cout << "Hi what is your name? ";
	getline(cin, name);
	clock_t end=clock();
	cout << "Time elapsed: " << double(diffclock(end,begin)) << " ms"<< endl;
	return 0;
}

The problem is, whenever I run it, the time elapsed is always 0. Is there something wrong in the code?
 
Technology news on Phys.org
Repeat action lots of time, take average time taken. Particularly for relatively simple function, a single call is going to take next to no time.
 
The following actually works with me:

Code:
#include <stdio.h>
#include <iostream.h>
#include <time.h>

double diffclock(clock_t clock1,clock_t clock2)
{
	double diffticks=clock1-clock2;
	double diffms=(diffticks*1000)/CLOCKS_PER_SEC;
	return diffms;
} 

int main (void)
{
        char c[1000]; 
	int i;
	clock_t begin=clock();
	cout << "Hi what is your name? ";
	cin >>c;
	clock_t end=clock();
	cout << "Time elapsed: " << double(diffclock(end,begin)) << " ms"<< endl;
	return 0;
}

the only difference is that I didn't use strings, and that I multiplied with 1000 to get the true number of milliseconds. The actual resolution of clock() is about 15 ms.
 
Hmm, strange that is still always 0 ms.
 
kamerling said:
The actual resolution of clock() is about 15 ms.
I've used the following:

QueryPerformanceCounter()
Highest resolution timer, but includes overhead from other tasks. Still I found it to be the best. Using SetThreadPriority() to bump up priority should reduce overhead from other tasks.

GetProcessTimes()
Supposed to exclude overhead from other processes, but seems to include interrupt overhead. timeBeginPeriod() (requires a later timeEndPeriod()) can be used increase the tick rate, but this also seems to increase the reported time, indicating that interrupt overhead is included in the process times.

clock()
A more generic time call. On Windows XP, reports time in milliseconds, but is based on a 64hz ticker, 15.625ms.
 
Last edited:
ACLerok, do you notice the difference between your code and kamerling's code? There are 1000 milliseconds in a second, not ten.
 
clock() doesn't necessarily have anything to do with time as measured by the clock on the wall -- it measures the time used by your process.

So, I imagine that in ACLerok's operating environment, the I/O function hands control over to the system. The net effect being that while your program is waiting for I/O, that time is attributed to the system, and not your process. So, on your system, it is correctly reporting that the computer spent zero milliseconds in the process executing your program.

It's "working" for kamerling because, on that system, time waiting for I/O is being attributed to the calling process.


If you want to report time as measured by your clock on the wall, you'll have to use gettimeofday, or make use of some non-standard timing functions supplied by your compiler or C library (or other source). Jeff Reid has listed some of the timing functions in the Windows API. If you aren't using that, try checking your compiler's or C library's manual. (_rtc is a common extension)



And, incidentally, some of those headers do not exist in C++. You should be using
#include <cstdio>
#include <ctime>



Actually, you shouldn't include cstdio either, because you aren't using any of the standard C streaming I/O functions.
 
Last edited:
Ummm... Found this thread with google, and I wanted to say that the C/C++ standard library has a tool for this known as difftime that returns time change in seconds as a floating point double. Seconds was enough precision for my uses, maybe for yours.

Example based on yours:

Code:
#include <iostream>
#include <time.h>
#include <string>

int main()
{
[INDENT]using namespace std;
string name;
time_t begin, end; 
time(&begin);
cout << "Hi what is your name? "; 
getline(cin, name);
time(&end);
cout << "Time elapsed: " << difftime(end, begin) << " seconds"<< endl;
return 0;[/INDENT]
}

Anyways, there you go if you haven't figured it out in the two years since this thread was last updated.

Also, in case you want to add the difftime to a string, may want to include this little bit of code that allows floating point numbers to be written to a string:

Code:
#include <sstream>
template <typename datatype>
inline std::string write(datatype data)
{
[INDENT]std::ostringstream oStream;
oStream << data;
return oStream.str();[/INDENT]
}

An example of its use are as follows:

Code:
int main()
{
[INDENT]using namespace std;
double test_number = 3.14159; //anybody want some pi?
string test_string(write(test_number));
//Or
string append_test_string = ""; //initiate it as a blank string...
append_test_string.append(write(test_number));
//both print the same thing
cout << test_string << endl;
cout << append_test_string << endl;[/INDENT]
};

Be careful what you try to add though, some complex data types may not work with that.

Anyways, have fun.
 

Similar threads

  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 23 ·
Replies
23
Views
3K
Replies
12
Views
3K
  • · Replies 8 ·
Replies
8
Views
4K
  • · Replies 6 ·
Replies
6
Views
12K
  • · Replies 4 ·
Replies
4
Views
6K
  • · Replies 118 ·
4
Replies
118
Views
10K
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 17 ·
Replies
17
Views
2K