# numstr2.py
# Written by Todd Wareham for CS 2500
"""
This script illustrates a basic timing analysis of comparing runtimes of
 several functions for creating strings of integers.

This analysis is implemented using the os.times() function.

Examples:
>>> numstrI(2)
'1'
>>> numstrI(4)
'1 2 4 '
>>> numstrJ(2)
'1'
>>> numstrJ(3)
'1 2 4 '
"""

import sys
import os


def numstrI(n):
    """
    Given an integer n > 0, returns string consisting of integers 1 through
     n inclusive.
    
    This function is implemented using the "+" string-concatenation operator.

    Examples:
        >>> numstrI(1)
        '1'
        >>> numstrI(3)
        '1 2 4 '
    """
    s = "1"
    for i in range(2,n + 1):
        s += (" " + str(i))
    return(s)


def numstrJ(n):
    """
    Given an integer n > 0, returns string consisting of integers 1 through
     n inclusive.
    
    This function is implemented using string-concatenation functions.

    Examples:
        >>> numstrJ(1)
        '1'
        >>> numstrJ(3)
        '1 2 4 '
    """
    t = ["1"]
    for i in range(2,n + 1):
        t.append(str(i))
    return " ".join(t)


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "usage: ", sys.argv[0], " <n>"
        sys.exit(1)
    
    if int(sys.argv[1]) < 1:
        print "error: n < 1"
        sys.exit(1)
    
    t0 = os.times()
    for i in range(1000):
        s = numstrI(int(sys.argv[1]))
    t1 = os.times()
    print ">>> numstrI (1000 executions):"
    print "  elapsed time = " + str(t1[4] - t0[4]) + " seconds"
    print "  user time    = " + str(t1[0] - t0[0]) + " seconds"
    print "  system time  = " + str(t1[1] - t0[1]) + " seconds"
    print "  CPU time     = " + str((t1[0] - t0[0]) + (t1[1] - t0[1])) + \
          " seconds"

    t0 = os.times()
    for i in range(1000):
        s = numstrJ(int(sys.argv[1]))
    t1 = os.times()
    print ">>> numstrJ (1000 executions):"
    print "  elapsed time = " + str(t1[4] - t0[4]) + " seconds"
    print "  user time    = " + str(t1[0] - t0[0]) + " seconds"
    print "  system time  = " + str(t1[1] - t0[1]) + " seconds"
    print "  CPU time     = " + str((t1[0] - t0[0]) + (t1[1] - t0[1])) + \
          " seconds"

