c++stringclasselapsedtime

Why are there a big difference when measuring elapsed time according to where to measure?


My question is about the difference of the elapsed time according to the point.

For finding the largest portion of the total elapsed time when executing in my code, I used clock function.

source : calculating time elapsed in C++

First, I put the clock function at the start and end of the main function. (Actually, there are some declaration of variables but I deleted them for readability of my questions). Then I think I will be able to measure the total elapsed time.

int main(){

    using clock = std::chrono::system_clock;
    using sec = std::chrono::duration<double>;
    const auto before = clock::now();

...

    std::cin >> a >> b;
    lgstCommSubStr findingLCSS(a,b,numberofHT,cardi,SubsA);

    const sec duration = clock::now() - before;

    std::cout << "It took " << duration.count() << "s in main function" << std::endl;

    return 0;
}

Second, I put the clock function at the class findingLCSS. This class is for finding longest common sub-string between two string. It is the class that actually do my algorithm. I write the code for finding it in its constructor. Therefore, when making this class, it returns longest common sub-string information. I think this elapsed time will be the actual algorithm running time.

public:
    lgstCommSubStr(string a, string b, int numHT, int m, vector <int> ** SA):
        strA(a), strB(b), hashTsize(numHT), SubstringsA(SA),
        primeNs(numHT), xs(numHT),
        A_hashValues(numHT), B_hashValues(numHT),
        av(numHT), bv(numHT), cardi(m)
{

        using clock = std::chrono::system_clock;
        using sec = std::chrono::duration<double>;
        const auto before = clock::now();
...

        answer ans=binarySearch(a,b, numHT);

        std::cout << ans.i << " " << ans.j << " " << ans.length << "\n";


        const sec duration = clock::now() - before;

        std::cout << "It took " << duration.count() << "s in the class" << std::endl;

}

The output is as below.

tool coolbox
1 1 3
It took 0.002992s in inner class
It took 4.13945s in main function

It means 'tool' and 'coolbox' have a substring 'ool'

But I am confused that there is a big difference between two times.

Because the first time is total time and the second time is algorithm running time, I have to think its difference time is the elapsed time for declaration variables.

But it looks weird because I think declaration variables time is short.

Is there a mistake in measuring the elapsed time?

Please give me a hint for troubleshoot. Thank you for reading!


Solution

  • Taking a snapshot of the time before std::cin >> a >> b; leads to an inaccurate measurement as you're likely starting the clock before you type in the values for a and b. Generally you want to put your timing as close as possible to the thing you're actually measuring.