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 programExplanation
!$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
Arrays and Vector Operations
Create and operate on arrays in modern Fortran.
Subroutines and Functions
Define reusable procedures in Fortran.
Modules and Derived Types
Organize code with modules and OOP-style types.
File I/O and Formatting
Read/write files with formatted output.
Numerical: Linear Algebra (BLAS/LAPACK)
Call BLAS/LAPACK for matrix operations.
Derived Types and Pointers
Custom types with allocatable components and pointers.