Timing and Statistics usage (with OpenMP)

  • Emilio Castro
  • 13/09/2020

Description

This example illustrates the use of FU_Prec, FU_Statistics and FU_Timing modules using a simple program. It generates a set of random numbers and then performs a lot of mean, variance and median calculations, and measures the time needed with different number of threads (using OpenMP).

Uses up to 7 OpenMP threads. Change this parameter accordingly.

Functions used

Code

PROGRAM FU_example1
   ! Example program for FU_Prec, FU_Statistics and FU_Timing modules of ecasglez's FortranUtilities.
   ! It repeats a lot of mean, variance and median calculations using random numbers.
   ! Uses OpenMP for parallel execution.
   ! compile using: gfortran example1.f90 -o example1 -fopenmp -I/path/to/include/ -lFortranUtilities -L/path/to/lib/ -O2
   ! before running: export LD_LIBRARY_PATH=/path/to/lib:${LD_LIBRARY_PATH}
   ! run using: ./example1
   ! license: MIT.

   !$   USE omp_lib
   USE FU_Prec      , ONLY: dp
   USE FU_statistics, ONLY: mean, variance, median
   USE FU_Timing    , ONLY: resetTotalTime, IntervalTIme, TotalTime

   IMPLICIT NONE

   INTEGER, PARAMETER :: max_num_threads = 7
   INTEGER, PARAMETER :: n = 1000
   REAL(KIND=dp),DIMENSION(:,:),ALLOCATABLE :: matrix
   REAL(KIND=dp),DIMENSION(n) :: media, varianza, mediana
   INTEGER :: i, k

   ALLOCATE(matrix(300000,n))

   DO i=1,n
      CALL random_number(matrix(:,i))
   END DO

   CALL resetTotalTime()
   DO k = 1, max_num_threads
!$    CALL omp_set_num_threads(k)
!$OMP PARALLEL DO
      DO i=1,n
         media(i) = mean(matrix(:,i))
         varianza(i) = variance(matrix(:,i))
         mediana(i) = median(matrix(:,i))
      END DO
!$OMP END PARALLEL DO
      WRITE(*,'(A,I0,A,F7.3,A)') 'Number of threads: ', k, '. Elapsed time: ', IntervalTime(), ' s.'
   END DO
   WRITE(*,'(A,F7.3,A)') 'Total elapsed time: ', TotalTime(), ' s.'

   DEALLOCATE(matrix)

END PROGRAM FU_example1

Compilation

Compile using the following command. Adjust paths accordingly.

gfortran example1.f90 -o example1 -fopenmp -I/path/to/include/ -lFortranUtilities -L/path/to/lib/ -O2

If no OpenMP libraries are available in your system, you can remove option -fopenmp. The code will work but there will not be any speedup.

Execution

Before running, since it has been compiled against the shared library:

export LD_LIBRARY_PATH=/path/to/lib:${LD_LIBRARY_PATH}

Then run with:

./example1

The output of the execution is:

Number of threads: 1. Time spent:  22.010 s.
Number of threads: 2. Time spent:  11.440 s.
Number of threads: 3. Time spent:   8.107 s.
Number of threads: 4. Time spent:   6.113 s.
Number of threads: 5. Time spent:   5.887 s.
Number of threads: 6. Time spent:   4.987 s.
Number of threads: 7. Time spent:   4.452 s.
Total time spent:  62.995 s.