koshachok
koshachok

Reputation: 510

Equal time execution for running with 4 and 8 threads

I test some code using OpenMP. Here it is:

#include <chrono>
#include <iostream>
#include <omp.h>

#define NUM_THREADS 8
#define ARR_SIZE 10000

class A {
private: 
    int a[ARR_SIZE];
public:
    A() {
        for (int i = 0; i < ARR_SIZE; i++)
            a[i] = i;
    }
// <<-----------MAIN CODE HERE--------------->
    void fn(A &o1, A &o2) {
        int some = 0;
        #pragma omp parallel num_threads(NUM_THREADS)
        {
            #pragma omp for reduction(+:some)
            for (int i = 0; i < ARR_SIZE; i++) {
                for (int j = 0; j < ARR_SIZE; j++)
                    some += o1.a[i] * o2.a[j];
            }
        }
        std::cout << some <<std::endl;
    }
};

int main() {
    A a,b,c;
    auto start = std::chrono::high_resolution_clock::now();
    c.fn(a,b);
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> elapsed = end - start;
    std::cout << elapsed.count();
}

Execution time:

P.S. My processor:

Model:               Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz 
CPU(s):              8
On-line CPU(s) list: 0-7
Thread(s) per core:  2
Core(s) per socket:  4
Socket(s):           1

Upvotes: 4

Views: 167

Answers (1)

zneak
zneak

Reputation: 138251

You have 4 physical cores. The promise of hyperthreading is that each core can "think about" two tasks, and will dynamically between the two when it gets blocked on one (for instance, if it needs to wait for a memory operation to finish). In theory, this means that the time wasted waiting for some operations to complete is reduced. However, in practice, actual performance gains tend to be nowhere close to the 2x improvement that you'd get by doubling the number of cores. The improvement is typically between 0 and 0.3x, and sometimes it even causes slowdowns.

4 threads is essentially the useful thread upper bound for the computer that you are using. A computer with 8 physical cores might get the speedup that you expect.

Upvotes: 4

Related Questions