KotlinIsland
KotlinIsland

Reputation: 869

C++ performance degradation (or code must be improved ?)

I am developping a simple program that copies the same string into another one in a loop. I use Visual Studio C++ 2019 Community Edition, and the project type is "Command line".

If I run it for 3,42 seconds then the calculated number of copies per second is 130 601 397, but if I run it for 77,97 seconds then the number of copies per second is 47 469 296...

The more time the program is running, the more performance degradation there is...

Here is the code :

#include <iostream>
#include <cstdlib>
#include <signal.h>
#include <chrono>
#include <string>

using namespace std;

unsigned long repeats_counter = 0;

std::chrono::steady_clock::time_point t1;
std::chrono::steady_clock::time_point t2;

// When CTRL+C (SIGINT), this is executed 
signal_callback_handler(int signum) {
    t2 = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = t2 - t1;
    std::cout << "Total execution time " << diff.count() << " s\n";
    unsigned long average_repeats_per_sec = (unsigned long)(repeats_counter / diff.count());
    std::cout << "Number of average repeats per second was " << 
    std::to_string(average_repeats_per_sec) << "\n";
    std::cout << "Number of average repeats per minute was " << 
    std::to_string(average_repeats_per_sec * 60) << "\n";
    cout << "Number of effective repeats = " << repeats_counter << endl;
    // Terminate program
    exit(signum);
}


int main()
{
    signal(SIGINT, signal_callback_handler);
    signal(SIGTERM, signal_callback_handler);

    std::string from_str, to_str;

    cout << "Start copying. CTRL+C to stop." << endl;
    t1 = std::chrono::high_resolution_clock::now();
    from_str = "the string to be copied";
    while (true) {
        to_str = from_str;
        repeats_counter++;
    }
    return 0;
}

Upvotes: 2

Views: 247

Answers (1)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14688

This could be caused by integer overflow. unsigned long is at least 32 bit and on on some platforms it is equal to unsigned int. unsigned long long partially alleviates the issue, but technically the loop should have some kind of defense against that, albeit it adds to the cost of loop.

There are two problems with code portability, omitted by compiler due to implementation:

  1. std::chrono::steady_clock::time_point should be std::chrono::high_resolution_clock::time_point
  2. signal_callback_handler should have return type void

Upvotes: 2

Related Questions