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
SUMMARY

This discussion focuses on measuring execution time in C++ using the clock() function from the time.h library. Users encountered issues with the reported time always being zero due to the short execution duration of simple functions. The solution involves using difftime() for better accuracy and considering higher-resolution timers like QueryPerformanceCounter(). Additionally, the discussion highlights the importance of understanding how I/O operations affect timing measurements.

PREREQUISITES
  • Familiarity with C++ programming language
  • Understanding of time measurement functions in C++
  • Knowledge of I/O operations and their impact on execution time
  • Basic understanding of the C++ standard library, particularly time.h
NEXT STEPS
  • Research QueryPerformanceCounter() for high-resolution timing in Windows
  • Explore difftime() for measuring time differences in seconds
  • Learn about gettimeofday() for wall-clock time measurement
  • Investigate the impact of I/O operations on performance timing in C++
USEFUL FOR

C++ developers, performance analysts, and anyone interested in accurate time tracking for function execution in programming.

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