I'm doing a project that involves comparing programming languages. I'm computing the Ackermann function. I tested Java, Python, and Ruby, and got responses between 10 and 30 milliseconds. But C++ seems to take 125 milliseconds. Is this normal, or is it a problem with the gettimeofday()
? Gettimeofday()
is in time.h.
I'm testing on a (virtual) Ubuntu Natty Narwhal 32-bit. I'm not short processing power (Quad-core 2.13 GHz Intel Xeon).
My code is here:
#include <iostream>
#include <sys/time.h>
using namespace std;
int a(int m,int n) {
if (m == 0) {
return n + 1;
} else if (m > 0 and n == 0) {
return a(m-1,1);
} else if (m > 0 and n > 0) {
return a(m-1,a(m,n-1));
}
}
int main() {
timeval tim;
gettimeofday(&tim,NULL);
double t1 = tim.tv_usec;
int v = a(3,4);
gettimeofday(&tim,NULL);
double t2 = tim.tv_usec;
cout << v << endl << t2-t1;
return 0;
}
Assuming you're talking about the resolution of the data returned (a), the POSIX specification for
gettimeofday
states:This is due to the fact that systems may have a widely varying capacity for tracking small time periods. Even the ISO standard
clock()
function includes caveats like this.If you're talking about how long it takes to call it (a), the standard makes no guarantees about performance along those lines. An implementation is perfectly free to wait 125 minutes before giving you the time although I doubt such an implementation would have much market success :-)
As an example of the limited resolution, I typed in the following code to check it:
The code basically records the changes in the underlying time, keeping a count of how many calls it took to
gettimeofday()
for the time to actually change. This is on my new i7 grunter laptop so it's not short on processing power (the count indicates how often it was able to callgettimeofday()
for each time quantum, aound the 5,000 mark).The output was:
showing that the resolution seems to be limited to no better than one thousand microseconds. Of course, your system may be different to that, the bottom line is that it depends on your implementation and/or environment.
(a) If you're talking about something else that I haven't thought of, you should probably flesh out your question with a little more detail. We're pretty good here on SO, but we're not omniscient.