Thread: Python Timer

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    2
    Rep Power
    0

    Python Timer


    I need a timer to start when my code is executed and to end when my code has run when a game has completed. To print the time taken in minutes and secs. To print a message at the end. Any ideas?
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    import datetime
    t1=datetime.datetime.now()
    ....your code...
    t2=datetime.datetime.now()
    #convert to seconds
    elpsd=(t2-t1)[0]*86400+(t2-t1)[1]+(t2-t1)[2]/1000000.0
    print "elapsed time: {0:12g} minutes".format(elpsd/60)
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    611
    Rep Power
    65
    One idea:
    Code:
    import time
    import sys
    
    # make this work with Python2 or Python3
    if sys.version_info[0] < 3:
        input = raw_input
    
    
    # seconds since epoch now at start
    start = time.time()
    
    # a silly game to test the counter
    a = input("Enter your name: ")
    b = input("Enter your age: ")
    c = input("Enter your weight: ")
    d = input("What year were you born? ")
    e = input("What is capitol of France? ")
    
    # the game is finished get seconds since epoch now
    end = time.time()
    
    elapsed = end - start
    
    print("This game took %d minutes and %d seconds" % (divmod(elapsed, 60)))
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    2
    Rep Power
    0

    Solutions


    Thanks for the solutions, I have have got them both working. I am new to Python, it looks like I have a long journey ahead.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    26
    Rep Power
    0
    sorry negate what I just wrote, I misread the question...

IMN logo majestic logo threadwatch logo seochat tools logo