Thread or Task

Puzzled which one to use so I decided to run a simple test, hopefully it helps;
What I used:

  • Utility function to simulate computation
  • Vector of futures
  • Async function
  • High precession clock

  • Utility function to simulate computation
    void simulate_work(double number, int nTimes) {
    std::cout << "Worker thread id= " << std::this_thread::get_id() << std::endl;
    for (int i = 0; i < nTimes; i++) {
        std::sqrt(number);
    }
    }
  • Vector of futures
    std::cout << "Main Thread ID: " << std::this_thread::get_id() << std::endl;
    std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
    std::vector<std::future<void>> futures;
  • Fire up the threads
    int nTimes = 10, nThreads = 5;
    for (int i = 0; i < nThreads; ++i) {
        futures.emplace_back(std::async(std::launch::async, simulate_work, 123456.78, nTimes));
    }
    for (const std::future<void> &ftr:futures) {
        ftr.wait();
    }
  • Calculate the impact
    std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();

There is a heavy penalty of 817 microsecond for firing up threads
file

Lets switch to tasks by changing the launch policy to deferred

    futures.emplace_back(std::async(std::launch::deferred, simulate_work, 123456.78, nTimes));

file

boom! We just optimized to a sweet 23 microseconds.

Hopefully I don't forget and repeat the experiement again. Cheers!

0