Fortran writing to /dev/null or NUL

1 minute read

Writing to /dev/null can save significant time on legacy Fortran programs that dump unneeded data to disk. This is lower risk than making modifications to non-standards compliant code, and certainly less programmer time consuming. I have seen 10x speedup from programs that had unneeded intensive file writing. It’s also particularly useful for Fortran code called from Python via f2py.

Null filename

Most OS use /dev/null, except for Windows NUL or NUL:.

  • Linux, Mac, BSD, Cygwin, Windows Subsystem for Linux: /dev/null
  • Windows: NUL

Example

Null-writing Fortran: devnull.f90

The test below is for 140 MBytes of data, where /dev/null is at least 5x faster than scratch file, even with fast SSD.

program nulltest
implicit none

real :: tic,toc
character(*), parameter :: nulunix='/dev/null', nulwin='NUL',fout='out.txt'
integer, parameter :: N=10000000
character(256) :: fn
integer :: ios,u,i

open(newunit=u, file=nulunix, iostat=ios)  ! Linux, Mac, Cygwin, WSL
if (ios /= 0) open(newunit=u,file=nulwin, iostat=ios)  ! Windows

inquire(unit=u, name=fn) ! find which filename is being used.

! --- benchmark NUL
call cpu_time(tic)
do i = 1,N
    write(u,*) 'blah blah blah'
    flush(u)
enddo
close(u) 
call cpu_time(toc)



print *,toc-tic,' seconds to write to',trim(fn)

!---- benchmark scratch
open(newunit=u, status='scratch')

call cpu_time(tic)
do i = 1,N
    write(u,*) 'blah blah blah'
    flush(u)
enddo
close(u)
call cpu_time(toc)


print *,toc-tic,' seconds to write to scratch file'

end program

Tags:

Categories:

Updated:

Leave a Comment