Reputation: 1511
I have a very simple function in C++:
double testSpeed()
{
using namespace boost;
int temp = 0;
timer aTimer;
//1 billion iterations.
for(int i = 0; i < 1000000000; i++) {
temp = temp + i;
}
double elapsedSec = aTimer.elapsed();
double speed = 1.0/elapsedSec;
return speed;
}
I want to run this function with multiple threads. I saw examples online that I can do it as follows:
// start two new threads that calls the "hello_world" function
boost::thread my_thread1(&testSpeed);
boost::thread my_thread2(&testSpeed);
// wait for both threads to finish
my_thread1.join();
my_thread2.join();
However, this will run two threads that each will iterate billion times, right? I want the two threads to do the job concurrently so the entire thing will run faster. I don't care about sync, it's just a speed test.
Thank you!
Upvotes: 0
Views: 1355
Reputation: 73490
There may be a nicer way, but this should work, it passes the range of variable to iterate over into the thread, it also starts a single timer before the threads are started, and ends after the timer after they're both done. It should be pretty obvious how to scale this up to more threads.
void testSpeed(int start, int end)
{
int temp = 0;
for(int i = start; i < end; i++)
{
temp = temp + i;
}
}
using namespace boost;
timer aTimer;
// start two new threads that calls the "hello_world" function
boost::thread my_thread1(&testSpeed, 0, 500000000);
boost::thread my_thread2(&testSpeed, 500000000, 1000000000);
// wait for both threads to finish
my_thread1.join();
my_thread2.join();
double elapsedSec = aTimer.elapsed();
double speed = 1.0/elapsedSec;
Upvotes: 3