! CPL wrapper around the gettimeofday system function
! ===================================================
!
! This function provides a REAL-valued clock in seconds, e.g. for timing
! program execution.
! It demonstrates how C functions can be used seamlessly in a CPL program
! It demonstrates the use of MODULEs to hide static variables

#include <sys/time.h>
! make C declarations available in this CPL program

REAL FUNCTION wallclock() FOLLOWS
! content of wallclock is inside the MODULE; this declares it globally

MODULE wallclock
  struct timeval startim       ! declaration using C struct declared in time.h
                               ! this static variable is local to the MODULE
  gettimeofday(startim,NULL)   ! libc function call
                               ! initializes startim when execution starts
  REAL FUNCTION wallclock()
    struct timeval tim
    gettimeofday(tim,NULL)     ! libc function call
    RESULT=(tim.tv_sec-startim.tv_sec)+1E-6*(tim.tv_usec-startim.tv_usec)
                               ! return time in seconds since program started
  END wallclock  !(function!)
END wallclock    !(module!)

! test example
!(
  REAL x=0
  WRITE "starting at " wallclock()
  LOOP FOR i=1 TO 10000
    x=x+SIN(i)
  REPEAT LOOP
  WRITE "ending at " wallclock()
!)