c++ - OpenMP C++ GCC 基本例程

标签 c++ bash gcc openmp hpc

我正在使用 openMP 在 C++ 中运行一个非常简单的例程并测量耗时......代码读取,

#include <iostream>
#include <math.h>
#include "timer.h"
#include <omp.h>



int main ()
{
    double start,finish;
    int i;
    int n=8000;
    double a[n];
    double b[n];
    double c[n];



    GET_TIME(start);
#pragma omp parallel private(i,a) shared(b,c,n)
    {
#pragma omp for 
        for (i=0; i<n-1; i++)
        b[i] += (a[i] + a[i+1])/2;
#pragma omp for
        for (i=0; i<n-1; i++)
            c[i] += (a[i] + a[i+1])/2;
    } 
    GET_TIME(finish);
    std::cout<< "Elapsed time is" <<(finish-start)<<"seconds";
    return 0;
}

我使用以下 bash 脚本编写代码(观察线程是在环境变量 OMP_NUM_THREADS=$n 中定义的):

#!/bin/bash

clear

g++ -O3 -o test test.cpp -fopenmp 

for n in $(seq 1 8); do
  export OMP_NUM_THREADS=$n
   ./test
    echo threads=$n
done

因此,观察到性能随着线程数量的增加而降低的一般趋势如下:(当然数字可以改变)...

Elapsed time is0.000161886secondsthreads=1
Elapsed time is0.00019002secondsthreads=2
Elapsed time is0.00226498secondsthreads=3
Elapsed time is0.000210047secondsthreads=4
Elapsed time is0.000212908secondsthreads=5
Elapsed time is0.00920105secondsthreads=6
Elapsed time is0.00937104secondsthreads=7
Elapsed time is0.000834942secondsthreads=8

有什么提高性能(而不是降低性能)的建议吗? 非常感谢!

最佳答案

你也可以这样做,它会增加每个线程完成的操作。这是为了通过实际让线程做更多工作来克服启动新线程所需的开销。此外,无需将 b、c 或 n 声明为共享。

#pragma omp parallel private(i,a,b,c,n)
{
#pragma omp for schedule(static)
    for (i=0; i<n-1; i++){
        b[i] += (a[i] + a[i+1])/2;
        c[i] += (a[i] + a[i+1])/2;}
}

关于c++ - OpenMP C++ GCC 基本例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32395428/

相关文章:

c++ - Linux 中 Eclipse C/C++ 的 Makefile

c++ - 将一个类传递给 sprintf

linux -/root/.bash_profile : line 16: syntax error: unexpected end of file

C 程序在一个系统上编译和运行,而不是在另一个系统上

c++ - 声明自身 (*this) 私有(private)的类以避免竞争条件/放弃 gcc 中线程私有(private)的请求

c++ - 将 vector 写入和读取到二进制文件

c++ - 使用 Visual C++ Express 2010 IDE 编译和使用 cl 命令在控制台下编译时的不同 exe 大小

Bash:如何将一个进程的 stdout 和 stderr 传递给两个不同的进程?

linux - 在值中存储 grep 时的额外反斜杠

c - 如何让cmd.exe中的GCC显示所有错误