C++: Sum up a large array, faster using std::async

Threading a string through a needle
Threading a string through a needle
Photo by amirali mirhashemian on Unsplash

With the powerful hardware available, summing up a large array of numbers does not take a lot of time. However, if you still want to shave off a few milliseconds you can sum up the array in parts and asynchronously.

Here is a quick example to use sum up an array using threading or asynchronously.

Code:

Output:

Single thread total = 400000000 in 831 milliseconds
Multi thread total = 400000000 in 387 milliseconds

As you can see, summing up the array in parts on a separate threads does provide a speed up. In this case, using three separate threads took less than half the time to complete, compared to the time taken by the single thread.

How many threads or in how many parts to split the a task for best performance figures depends on the task at hand and the hardware you are deploying on.

Computer Vision | Machine Learning | Deep Learning https://arccoder.github.io/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store