In the above code,#pragma omp parallel for
The function of this line is to invoke the function of OpenMP, depending on the number of cores detected, the for (i = 0; i < 1000000000; i++) This loop execution process is evenly distributed to each CPU core.
Removing the #pragma omp parallel for this line is consistent with the normal serial code effect.
Note that to use OpenMP functionality, you need to add -fopenmp compilation parameters when compiling.
Here are the two 4 kinds of results that are compiled and paired with two kinds of code, and you can see the effect visually:
1, the code contains #pragma omp parallelfor, compile parameters have -fopenmp
Endys-macbook-pro:desktop endy$ VI test.c
Endys-macbook-pro:desktop endy$ gcc-6 Test.c-o test-fopenmp
Endys-macbook-pro:desktop endy$./test
Program costs 50202611.00 clock tick.
2, the code contains #pragma omp parallelfor, the compilation parameters are not -fopenmp
Endys-macbook-pro:desktop endy$ gcc-6 test.c-o test
Endys-macbook-pro:desktop endy$./test
Program costs 4068178.00 clock tick.
3, the code does not #pragma omp parallelfor, compile parameters have -fopenmp
Endys-macbook-pro:desktop endy$ VI test.c
Endys-macbook-pro:desktop endy$ gcc-6 Test.c-o test-fopenmp
Endys-macbook-pro:desktop endy$./test
Program costs 4090744.00 clock tick.
4, the code does not #pragma omp parallelfor, the compilation parameters are not -fopenmp
Endys-macbook-pro:desktop endy$ VI test.c
Endys-macbook-pro:desktop endy$ gcc-6 test.c-o test
Endys-macbook-pro:desktop endy$./test
Program costs 4170093.00 clock tick.
As can be seen, only in case 1, OpenMP in force, the other 3 cases, are single-core operation, 2, 3, 4 results are closer, and 1 of the running result is about 25%.
It is worth noting that the use of multi-core case 1 is 25% slower than the other 3 types of the single core, because in this single loop operation, the parallel allocation of CPU tasks is less efficient than the direct execution of the next circular instruction. Therefore, it is not possible to use parallel operations to improve the efficiency of operations, according to the actual situation to judge.
How the C + + OpenMP Parallel program maximizes CPU usage on multi-core Linux