I'm interested in comparing CPU times some code portions written C++ vs Python (running on Linux). Will the following methods produce a "fair" comparison between the two?
Python
Using the resource module:
import resource
def cpu_time():
return resource.getrusage(resource.RUSAGE_SELF)[0]+\ # time in user mode
resource.getrusage(resource.RUSAGE_SELF)[1] # time in system mode
which allows for timing like so:
def timefunc( func ):
start=cpu_time()
func()
return (cpu_time()-start)
Then I test like:
def f():
for i in range(int(1e6)):
pass
avg = 0
for k in range(10):
avg += timefunc( f ) / 10.0
print avg
=> 0.002199700000000071
C++
Using the ctime
lib:
#include <ctime>
#include <iostream>
int main() {
double avg = 0.0;
int N = (int) 1e6;
for (int k=0; k<10; k++) {
clock_t start;
start = clock();
for (int i=0; i<N; i++) continue;
avg += (double)(clock()-start) / 10.0 / CLOCKS_PER_SEC;
}
std::cout << avg << '\n';
return 0;
}
which yields 0.002
.
Concerns:
- I've read that C++
clock()
measures CPU time which is what I'm after, but I can't seem to find if it includes both user and system times. - Results from C++ are much less precise. Why is that?
- Overall fairness of comparison as mentioned.
Update
updated the c++ code as per David's suggestion in the comments:
#include <sys/resource.h>
#include <iostream>
int main() {
double avg = 0.0;
int N = (int) 1e6;
int tally = 0;
struct rusage usage;
struct timeval ustart, ustop, sstart, sstop;
getrusage(RUSAGE_SELF, &usage);
ustart = usage.ru_utime;
sstart = usage.ru_stime;
for (int k=0; k<10; k++) {
ustart = usage.ru_utime;
sstart = usage.ru_stime;
for (int i=0; i<N; i++) continue;
getrusage(RUSAGE_SELF, &usage);
ustop = usage.ru_utime;
sstop = usage.ru_stime;
avg += (
(ustop.tv_sec+ustop.tv_usec/1e6+
sstop.tv_sec+sstop.tv_usec/1e6)
-
(ustart.tv_sec+ustart.tv_usec/1e6+
sstart.tv_sec+sstart.tv_usec/1e6)
) / 10.0;
}
std::cout << avg << '\n';
return 0;
}
Running:
g++ -O0 cpptimes.cpp ; ./a.out
=> 0.0020996
g++ -O1 cpptimes.cpp ; ./a.out
=> 0
So I suppose getrusage
gets me a little bit better resolution, but I'm not sure how much I should read into it. Setting the optimization flag certainly makes a big difference.