有没有人能提供一个OpenMP程序,与没有它相比,它的加速是可见的。我发现很难加速。甚至这个简单的程序在OpenMP中运行得也比较慢。我的处理器是Intel®Core™i3-2370M [email protected]×4,运行在Linux上(Ubuntu14.10)

#include <cmath>
#include <stdio.h>
#include <time.h>
int main() {
   clock_t t;
   t = clock();
   const int size = 4;
   long long int k;

    #pragma omp parallel for num_threads(4)
    for(int n=0; n<size; ++n) {
       for(int j=0;j<100000000;j++){
       }
       printf("\n");
    }

    t = clock() - t;
    printf ("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);

    return 0;
}

最佳答案

我遇到了一个与此相关的问题,我想找到数组的最大值。我犯了和你一样的错误,我用时钟来测量经过的时间。为了解决这个问题,我使用clock_ghtime()代替,现在它可以工作了。
对于速度可测量的示例代码(请注意,您可能希望更改N的值):

#include <omp.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>

struct timespec diff(struct timespec start, struct timespec end)
{
struct timespec temp;

if(end.tv_sec - start.tv_sec == 0)
{
    temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
else
{
    temp.tv_nsec = ((end.tv_sec - start.tv_sec)*1000000000) + end.tv_nsec - start.tv_nsec;
}

return temp;
}

int main()
{
unsigned int N;
struct timespec t_start, t_end;
clock_t start, end;

srand(time(NULL));

FILE *f = fopen("out.txt", "w");
if(f == NULL)
{
    printf("Could not open output\n");
    return -1;
}

for(N = 1000000; N < 100000000; N += 1000000)
{
    fprintf(f, "%d\t", N);
    int* array = (int*)malloc(sizeof(int)*N);
    if(array == NULL)
    {
        printf("Not enough space\n");
        return -1;
    }
    for(unsigned int i = 0; i<N; i++) array[i] = rand();

    int max_val = 0.0;

    clock_gettime(CLOCK_MONOTONIC, &t_start);

    #pragma omp parallel for reduction(max:max_val)
    for(unsigned int i=0; i<N; i++)
    {
        if(array[i] > max_val) max_val = array[i];
    }

    clock_gettime(CLOCK_MONOTONIC, &t_end);

    fprintf(f, "%lf\t", (double)(diff(t_start, t_end).tv_nsec / 1000000000.0));

    max_val = 0.0;

    clock_gettime(CLOCK_MONOTONIC, &t_start);
    for(unsigned int i = 0; i<N; i++)
    {
        if(array[i] > max_val) max_val = array[i];
    }
    clock_gettime(CLOCK_MONOTONIC, &t_end);

    fprintf(f, "%lf\n", (double)(diff(t_start, t_end).tv_nsec / 1000000000.0));

    free(array);
}

fclose(f);

return 0;
}

关于c - 带有加速功能的示例openmp程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29615285/

10-12 15:04