CroCo CroCo - 9 months ago 43
C Question

performance of system clock in c and c++11

I have noticed that C-style to compute the elapsed time is faster than if I do it using C++11. The difference is getting smaller if the execution needs more time.

#include <iostream>
#include <chrono>
#include <ctime>

long fibonacci(int n)
if (n < 3) return 1;
return fibonacci(n-1) + fibonacci(n-2);

int main()
/* C++11-Style */
std::chrono::time_point<std::chrono::system_clock> start, end;

/* C-Style */
clock_t c_start, c_end;
double c_elapsed;

/* Start */
start = std::chrono::system_clock::now();
c_start = clock();

std::cout << "f(30) = " << fibonacci(30) << '\n';

/* End */
c_end = clock();
end = std::chrono::system_clock::now();

/* Compute Elasped time */
c_elapsed = ((double)(c_end-c_start))/CLOCKS_PER_SEC;
std::chrono::duration<double> elapsed_seconds = end-start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);

std::cout << "finished computation at " << std::ctime(&end_time)
<< " elapsed time: " << elapsed_seconds.count() << "s\n";
std::cout << "c_elapsed time: " << c_elapsed << "s" << std::endl;

The result is

f(30) = 832040
finished computation at Fri Jul 4 05:03:10 2014
elapsed time: 0.00417783s (C++11)
c_elapsed time: 0.003686s (C)

Why this is the case?

Answer Source

Your test is hardly fair! This is for several reasons.

Broken benchmarking

You have clock() calls surrounding only the fibonacci calculation, but std::chrono::system_clock::now() calls surrounding the fibonacci calculation plus two clock() calls!

Let's look at that again:

  C                | C++11
  fibonacci(30)    | clock()
                   | fibonacci(30)
                   | clock()

It seems wholly reasonable that your C++11 version should result in a higher duration.

Re-run your benchmark with isolated mechanisms (such as an entirely separate file for each variant of code), and also increase the size of the calculation being timed to get more meaningful results; run it 100 times and take an average, or something.

Different semantics

That being said, I am seeing fairly consistently that clock() is slower:

#include <ctime>
#include <chrono>

int main()
    for (size_t i = 0; i < 20000; i++)
#ifdef CSTYLE
g++ -std=c++11 -O2 -Wall -pedantic main.cpp && time ./a.out &&
g++ -std=c++11 -O2 -Wall -pedantic -DCSTYLE main.cpp && time ./a.out
real  0m0.027s
user  0m0.008s
sys   0m0.016s

real  0m0.038s
user  0m0.000s
sys   0m0.036s

I don't know why this is but, consequently, comparing elapsed_seconds.count() and c_elapsed and expecting to make any firm rationalisations about the result is largely folly.