I'm iterating over a vector of structs and processing each struct individually.
It looks something like this:
for_each(begin(data),end(data),DoTask);
//assume "data" is std::vector<DataT>
//assume DoTask is a function that takes a DataT by reference
The code is significantly slow because DoTask connects to particular websites and analyzes HTML.
What would be the best way to speed this up?
My goal is to analyze multiple DataTs at the same time.
I'm very new to threading, but std::async and std::future look promising.
Looping Performance in C++ Today I was testing the performance of a piece of code, which is basically accessing each element in a container within a for loop. But the result is quite shocking because I found the std::for_each version is 10 times faster than the raw loop.
Syntax: for_each (InputIterator start_iter, InputIterator last_iter, Function fnc) start_iter : The beginning position from where function operations has to be executed. last_iter : The ending position till where function has to be executed.
std::for_each is an STL algorithm that takes a collection of elements (in the form of a begin and end iterator) and a function (or function object), and applies the function on each element of the collection. It has been there since C++98.
You can do something like this
for(T& d : data) std::thread(DoTask, d).detach();
Or you can use something more complicated like Intel's Thread Building Blocks and the parallel_for
(isn't that the name?) function thereof.
Are you using GCC? Recent versions have a parallel version of for_each
(see here for how to use it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With