mercredi 21 août 2019

Why is (n += 2 * i * i) faster than (n+= i) in C++?

This C++11 program takes on average between 7.42s and 7.79s to run.

#include <iostream>
#include <chrono>

using namespace std;
using c = chrono::system_clock;
using s = chrono::duration<double>;

void func(){

    int n=0;
    const auto before = c::now();
    for(int i=0; i<2000000000; i++){
        n += i;
    }
    const s duration = c::now() - before;
    cout << duration.count() << "s" << endl;

}

if I replace n += i with n += 2 * i * i it takes between 5.80s and 5.96s. how come?

I ran each version of the program 20 times, alternating between the two. Here are the results:

n += i   |  n += 2 * i * i
---------+----------------
7.77047  |  5.87978
7.69226  |  5.83551
7.77375  |  5.84888
7.73748  |  5.84629
7.72988  |  5.84356
7.69736  |  5.83784
7.72597  |  5.84246
7.72722  |  5.81678
7.73291  |  5.81237
7.71871  |  5.81016
7.7478   |  5.80119
7.64906  |  5.80058
7.7253   |  5.9078
7.42734  |  5.96399
7.72573  |  5.84733
7.65591  |  5.81793
7.76619  |  5.83116
7.76963  |  5.84424
7.79928  |  5.87078
7.79274  |  5.84689

Aucun commentaire:

Enregistrer un commentaire