Measuring Time Elapsed in C++: A Guide for Accurate Time Tracking

In summary, the code is not measuring the time it takes for the function to execute, but the time it takes for the function to return. The code is trying to use the time return to calculate the time it took for the function to execute, but it keeps reporting zero milliseconds. The code that works is the same code as posted, but uses timeBeginPeriod() and timeEndPeriod() to increase the tick rate, so that the interrupt overhead is not counted.
  • #1
ACLerok
194
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
  • #2
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.
 
  • #3
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.
 
  • #4
Hmm, strange that is still always 0 ms.
 
  • #5
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:
  • #6
ACLerok, do you notice the difference between your code and kamerling's code? There are 1000 milliseconds in a second, not ten.
 
  • #7
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:
  • #8
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.
 

1. How can I measure the time elapsed in my C++ program?

In order to measure time elapsed in your C++ program, you can use the std::chrono library. This library provides high-precision timing functionality, allowing you to accurately measure elapsed time in your code.

2. What is the difference between CPU time and wall-clock time?

CPU time refers to the amount of time that the processor spends executing your code. Wall-clock time, on the other hand, includes not only the time spent executing your code, but also any delays or waiting time that may occur due to external factors such as input/output operations or system processes.

3. How can I measure time elapsed in milliseconds?

You can measure time elapsed in milliseconds by using the std::chrono::milliseconds class in the std::chrono library. This class represents a duration in milliseconds and can be used to accurately measure elapsed time in your program.

4. Can I measure the time elapsed between specific points in my code?

Yes, you can use the std::chrono::steady_clock class in the std::chrono library to measure the time elapsed between specific points in your code. This class provides a steady clock that guarantees a monotonic progression of time, making it suitable for measuring intervals.

5. How can I improve the accuracy of my time measurements?

To improve the accuracy of your time measurements, you can use a high-resolution clock, such as std::chrono::high_resolution_clock, which provides the highest possible resolution for timing. Additionally, you should also consider repeating your measurements multiple times and taking the average to reduce the impact of any external factors on your timing results.

Similar threads

  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
6
Views
8K
  • Programming and Computer Science
2
Replies
39
Views
3K
  • Programming and Computer Science
4
Replies
118
Views
6K
  • Programming and Computer Science
Replies
8
Views
2K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
5
Views
4K
  • Programming and Computer Science
Replies
30
Views
2K
  • Programming and Computer Science
Replies
17
Views
1K
Back
Top