Home > Software design >  What is the fastest way to get seconds passed in cpp?
What is the fastest way to get seconds passed in cpp?

Time:12-17

I made a factoring program that needs to loop as quickly as possible. However, I also want to track the progress with minimal code. To do this, I display the current value of i every second by comparing time_t start - time_t end and an incrementing value marker.

    using namespace std; // cause I'm a noob

    // logic stuff
    int divisor = 0, marker = 0;
    int limit = sqrt(num);
    for (int i = 1; i <= limit; i  ) // odd number = odd factors
    {
        if (num % i == 0)
        {
            cout << "\x1b[2K" << "\x1b[1F" << "\x1b[1E"; // clear, up, down
            if (i != 1)
                cout << "\n";
            divisor = num / i;
            cout << i << "," << divisor << "\n";
        }


        end = time(&end); // PROBLEM HERE

        if ((end - start) > marker)
        {
            cout << "\x1b[2K" << "\x1b[1F" << "\x1b[1E"; // clear, up, down
            cout << "\t\t\t\t" << i;
            marker  ;
        }
    }

Of course, the actual code is much more optimized and uses boost::multiprecision, but I don't think that's the problem. When I remove the line end = time(&end), I see a performance gain of at least 10%. I'm just wondering, how can I track the time (or at least approximate seconds) without unconditionally calling a function every loop? Or is there a faster function?

CodePudding user response:

You observe "When I remove the line end = time(&end), I see a performance gain of at least 10%." I am not surprised, reading time easily is taking inefficient time, compared to doing pure CPU calculations.

I assume hence that the time reading is actually what eats the performance which observe lost when removing the line.

You could use an estimation of the minimum number of iterations your loop does within a second and then only check the time if multiples of (half of) that number have looped.
I.e., if you only want to be aware of time in a resolution of seconds, then you should try to only marginally more often do the time-consuming reading of the time.

CodePudding user response:

I would use a totally different approach where you seperate measurement/display code from the loop completely and even run it on another thread. Live demo here : https://onlinegdb.com/8nNsGy7EX

#include <iostream>
#include <chrono>           // for all things time
#include <future>           // for std::async, that allows us to run functions on other threads

void function()
{
    const std::size_t max_loop_count{ 500 };
    std::atomic<std::size_t> n{ 0ul };          // make access to loopcounter threadsafe

    // start another thread that will do the reporting independent of the
    // actual work you are doing in your loop.
    // for this capture n (loop counter) by reference (so this thread can look at it)
    auto future = std::async(std::launch::async,[&n, max_loop_count]
    {
        while (n < max_loop_count)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            std::cout << "\rprogress = " << (100 * n) / max_loop_count << "%";
        }
    });

    // do not initialize n here again. since we share it with reporting    
    for (; n < max_loop_count; n  )
    {
        // do your loops work, just a short sleep now to mimmick actual work
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    // synchronize with reporting thread
    future.get();
}

int main()
{
    function();
    return 0;
}

If you have any questions regarding this example let me know.

  • Related