Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22475

-pthread and OpenMP independently and implicitly affect the running time of the program

$
0
0

I am trying to study the speed change with and without OpenMP.
To do this, I wrote the following program:
#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#include <omp.h>#include <time.h>#define ARRAY_SIZE 1024struct timespec start_time = {0}, finish_time = {0};long time_delta = 0;void bubble_sort(unsigned int* array) {    unsigned int tmp = 0;    bool no_swap = 0;    for (unsigned int i = ARRAY_SIZE - 1; i >= 0; --i)    {        no_swap = 1;        {            for (unsigned int j = 0; j < i; j++)            {                if (array[j] > array[j + 1])                {                    tmp = array[j];                    array[j] = array[j + 1];                    array[j + 1] = tmp;                    no_swap = 0;                }            }        }        if (no_swap)            break;    }}int main(int argc, char* argv[]) {    (void)argc;    (void)argv;    srand(time(NULL));    unsigned int* array = malloc(sizeof(unsigned int) * ARRAY_SIZE);    if(!array) { return -1; }    for(unsigned int i = 0; i < ARRAY_SIZE; ++i) {        array[i] = rand() % ARRAY_SIZE;    }    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);    bubble_sort(array);    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &finish_time);    time_delta = (1000000000 * (finish_time.tv_sec - start_time.tv_sec)) + (finish_time.tv_nsec - start_time.tv_nsec);    printf("Time: %li\n", time_delta);    free(array);    return 0;}

For normal compilation using:
gcc main.c -o prog
for n in {1..10}; do ./prog; done
I get this result:

Time: 2278455Time: 1979448Time: 2070140Time: 2266056Time: 2600376Time: 2049736Time: 2067162Time: 2076334Time: 2241909Time: 2088248

However, if I add -fopenmp and don't change the code , I will get the following result in time:

Time: 1333565Time: 1894499Time: 1278883Time: 1966811Time: 1281771Time: 1290650Time: 1470460Time: 1392590Time: 1277663Time: 1273773

Why did the program start working faster only when adding OpenMP to the compiler?
Thus, I can't adequately measure the impact of any OpenMP directives on my work time.
I noticed that -pthread automatically turns on -fopenmp, and it is this that makes the program run into the program faster, by itself.

Thanks.


Viewing all articles
Browse latest Browse all 22475

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>