# L-37 MCS 275 Wed 16 Apr 2008 : time_filework.py

# Illustration of os.times to study the cost
# of working with files.

def NumbersOnFile(n):
   """
   Takes n numbers uniformly in [0,1]
   and writes the numbers to a file.
   Closes and reopens the file to
   find the largest number.
   """
   from random import uniform as u
   file = open('/tmp/work','w')
   for i in range(0,n):
      file.write(str(u(0,1)) + '\n')
   file.close()
   max = 0
   file = open('/tmp/work','r')
   while True:
      d = file.readline()
      if d =='': break
      x = float(d[:-1])
      if x > max: max = x
   print 'max = ', max

def main():
   """
   Calls NumbersOnfFile.
   """
   import os
   n = 1000000
   a = os.times()
   NumbersOnFile(n)
   b = os.times()
   print 'user cpu time : %.4f' % (b[0] - a[0])
   print '  system time : %.4f' % (b[1] - a[1])
   print ' elapsed time : %.4f' % (b[4] - a[4])

if __name__=="__main__": main()
