# L-29 MCS 260 Friday 20 March 2015 : time_filework.py
"""
Illustration of os.times to study the cost
of working with files.
"""

def numbers_on_file(nbr):
    """
    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
    workfile = open('work', 'w')
    for _ in range(nbr):
        workfile.write(str(u(0, 1)) + '\n')
    workfile.close()
    maxnum = 0.0
    workfile = open('work', 'r')
    while True:
        line = workfile.readline()
        if line == '':
            break
        data = float(line[:-1])
        if data > maxnum:
            maxnum = data
    print('max = ', maxnum)

def main():
    """
    Calls numbers_on_file.
    """
    import os
    nbr = 1000000
    start = os.times()
    numbers_on_file(nbr)
    stop = os.times()
    print('user cpu time : %.4f' % (stop[0] - start[0]))
    print('  system time : %.4f' % (stop[1] - start[1]))
    print(' elapsed time : %.4f' % (stop[4] - start[4]))

if __name__ == "__main__":
    main()
