Multithreading slower than single threading

I writing a program that does heavy calculations for large arrays in real-time. The task can be split into several sub-arrays for multithreading. However, I cannot run this any faster using threads.

Here is a sample dummy code which was created for demonstration (same problem). Two threads-version ends up lasting 39 seconds, which is couple of seconds longer if they were computed one after another(!). It doesn't matter if the arrays are global etc. I also tested using "thread constructors" only once, but with the same result.

I'm using XCode (5.1.1) and Macbook Air (2013 model, Core i5, Os X 10.8.5). Yes, this is old computer, I'm rarely programming...

So, could you find any mistake in the logic I have in the code or could it be somewhere in the settings of Xcode etc?

#include <ctime>
#include <iostream>
#include <thread>

class Value
    float a[3000000];

void cycle(Value *val)
    int i;
    for (i=0; i<3000000; i++)

int main()
    Value *val1=new Value, *val2=new Value;
    clock_t start,stop;
    for (int i=0; i<1000; i++)
        thread first (cycle,val1);
        thread second (cycle,val2);
    float tdiff=(((float)stop - (float)start) / 1000000.0F);
    std::cout<<endl<<"This took "<<tdiff<<" seconds...";
    return 0;

Read more here:

Content Attribution

This content was originally published by Bear Productions at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: