在CentOS中,Fortran支持多種并行計算技術,主要包括OpenMP和MPI。以下是詳細信息:
program parallel_loop
use omp_lib
implicit none
integer :: i, n
real, allocatable :: a(:), b(:)
n = 1000000
allocate(a(n), b(n))
! 初始化數組
a = 1.0
b = 2.0
! 并行計算
!$omp parallel do
do i = 1, n
a(i) = a(i) * b(i)
end do
!$omp end parallel do
! 打印結果的前5個元素
print *, 'First 5 elements of array a:'
print *, a(1:5)
deallocate(a, b)
end program parallel_loop
gfortran -fopenmp -o parallel_example parallel_example.f90
./parallel_example
program mpi_example
use mpi
implicit none
integer :: rank, size, ierr, i
integer, parameter :: n = 100
real, allocatable :: local_sum, global_sum
call mpi_init(ierr)
call mpi_comm_rank(MPI_COMM_WORLD, rank, ierr)
call mpi_comm_size(MPI_COMM_WORLD, size, ierr)
allocate(a(n))
a = real(rank) * 1.0
! 每個進程計算部分和
local_sum = 0.0
do i = 1, n
local_sum = local_sum + a(i)
end do
! 所有部分和相加得到全局和
call mpi_reduce(local_sum, global_sum, 1, MPI_REAL, MPI_SUM, 0, MPI_COMM_WORLD, ierr)
if (rank == 0) then
print *, 'Global sum:' , global_sum
end if
deallocate(a)
call mpi_finalize(ierr)
end program mpi_example
mpif90 -o mpi_example mpi_example.f90
mpirun -np 4 ./mpi_example
通過這些技術,Fortran在CentOS平臺上提供了強大的并行計算能力,可以顯著提高科學計算和工程應用的效率和性能。