Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time measure script in python

Tags:

python

I received the following script from a fellow programmer:

    from time import *
    start = strptime(asctime())
    end = strptime(asctime())
    print 'you took %i minutes' % (end[4] - start[4])

As you might already know, the script measures the time between the third and fourth line. However, it seems to measure it in minutes. How can I go about to measure it in seconds, with at least one decimal place (ex. 7.4 seconds).

Also, I would like to add one extra piece of functionality. Say the script runs, and I am asked by the program to type any word. At the end of my typing, I have to press the enter key to exit the program and measure the time from the first keystroke to the moment I press enter. How can I go about measuring this?

like image 539
Nico Bellic Avatar asked Feb 03 '12 17:02

Nico Bellic


1 Answers

First, I would avoid using import * as it's considered bad practice. You can use time.time() to get more precision:

>>> import time
>>> start = time.time()
>>> end = time.time()
>>> end - start
5.504057168960571

You could also use datetime.datetime.now().

like image 119
jterrace Avatar answered Sep 28 '22 07:09

jterrace