example3_performance_critical.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <cstdint>
#include <iostream>
#include <chrono>

uint_fast32_t fibonacci(uint_fast8_t n) {
    if (n <= 1) return n;
    uint_fast32_t a = 0, b = 1;
    for (uint_fast8_t i = 2; i <= n; ++i) {
        uint_fast32_t temp = a + b;
        a = b;
        b = temp;
    }
    return b;
}

int main() {
    const int iterations = 1000000;
    auto start = std::chrono::high_resolution_clock::now();

    for (int i = 0; i < iterations; ++i) {
        fibonacci(30);
    }

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;

    std::cout << "Time to calculate fibonacci 1,000,000 times: " << diff.count() << " s" << std::endl;

    return 0;
}
Back to cstdint