Jump to content

[C++] Masurarea timpului


Recommended Posts

In acest tutorial am decis sa masuram performanta executarii a doua bucati de cod diferite. Am ales doua metode diferite de a calcula restul impartirii lui X la Y, fara a folosi operatorul %.

#include <chrono> // pentru calcularea timpului
#include <iostream> // pentru input si output

const int number_of_tests = 1e5; // numarul de teste rulate

int calc_remainder_with_repeated_substractions(int x, int y)
    while (x >= 0) {
        x -= y;
    x += y;

    return x;

int calc_remainder_with_math_formula(int x, int y) {
    return x - y * (x / y);

int main() {
    std::chrono::steady_clock::time_point begin, end; // initializarea variabilelor de timp

    begin = std::chrono::steady_clock::now(); // momentul in care incepe executia codului
    for (int i = 0; i < number_of_tests; ++i) {
        calc_remainder_with_repeated_substractions(1e5, 7); // codul pe care dorim sa-l rulam si sa vedem cat dureaza
    end = std::chrono::steady_clock::now(); // momentul in care se termina executia codului
    std::cout << "calc_remainder_with_repeated_substractions: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "ms\n\n"; // diferenta de timp

    begin = std::chrono::steady_clock::now();
    for (int i = 0; i < number_of_tests; ++i) {
        calc_remainder_with_math_formula(1e5, 7);
    end = std::chrono::steady_clock::now();
    std::cout << "calc_remainder_with_math_formula: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "ms\n\n";

    return 0;


calc_remainder_with_repeated_substractions: 2339667ms

calc_remainder_with_math_formula: 2495ms

Observam ca daca vrem sa aflam de 10.000 de ori restul impartirii numarului 10.000 la 7 cu prima metoda, avem nevoie de 2.3396s pe cand daca folosim a 2-a metoda, observam o crestere in performanta, codul ruland in 0.0024s.


Prima metoda este inspirata din acest tutorial.

Edited by Vesca
Link to comment
Share on other sites

This topic is now closed to further replies.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.