What's the right way to count the thread run time?

Viewed 40

Like this:

    thread t1(getPrimes,begin,end, ref(vect));
    start = chrono::high_resolution_clock::now();
    t1.join();
    finish = chrono::high_resolution_clock::now();

Or like this:

    start = chrono::high_resolution_clock::now();
    thread t1(getPrimes,begin,end, ref(vect));
    t1.join();
    finish = chrono::high_resolution_clock::now();

Should I start it before or after thread t1?

1 Answers

The beginning of a new execution thread is sequenced only with the completion of std::thread's constructor.

In the first version, the entire execution thread could theoretically run and finish before the original execution thread calls now() for the first time. C++ gives you no guarantees whatsoever that the execution thread won't actually start and run only after the first call to now.

The second version is guaranteed to cover the entire execution thread, plus a little bit of overhead of std::thread's construction.

Even better would be to move the run time capture into the actual execution thread itself.

Related