Skip to content
Fortran

OpenMP Parallelism

Parallelize loops with OpenMP directives.

By EZ4Code Team
openmpparallelperformance

Code

program parallel
  use omp_lib
  implicit none
  integer, parameter :: n = 1000000
  real :: a(n), b(n), c(n)
  integer :: i
  real :: start, finish

  ! Initialize
  a = 1.0; b = 2.0

  call cpu_time(start)

  ! Parallel loop
  !$omp parallel do
  do i = 1, n
    c(i) = a(i) + b(i) * sqrt(real(i))
  end do
  !$omp end parallel do

  call cpu_time(finish)
  print *, 'Time:', finish - start
  print *, 'c(1), c(n):', c(1), c(n)

  ! Reduction
  real :: total
  total = 0.0
  !$omp parallel do reduction(+:total)
  do i = 1, n
    total = total + c(i)
  end do
  !$omp end parallel do
  print *, 'Sum:', total
end program

Explanation

!$omp parallel do splits the loop across threads — must compile with -fopenmp (gfortran) or /Qopenmp (Intel). Iterations must be independent (no cross-iteration dependencies). reduction(+:total) safely accumulates a sum across threads. Use cpu_time or omp_get_wtime for timing. Set thread count via OMP_NUM_THREADS env var.

More Fortran Snippets