Simple Process Timer in Python.

Profiling code is important.

In python, the easiest way to time your code is to do the following:

from datetime import datetime
start = datetime.now()
# Some long-running process
end = datetime.now()
print "process run in %s" % (end - start)

This solution works, but it can be annoying to write, and you’ll have to remove the debug lines before you ship your code to production. Once or twice, this is okay. But doing it over and over again can get annoying.

Do this in one line:

with timer() as t:
    print "Hello, world!"
    # Some long-running process.

which returns

Hello world!
process run in 0:00:00.001030

It’s cleaner, and you can easily toggle it if your application is off of DEBUG mode. Code below:

from datetime import datetime
import time
 
class timer:
    def __enter__(self):
        self.start = datetime.now()
        return self
 
    def __exit__(self, type, value, traceback):
        self.end = datetime.now()
        print "time: %s" % (self.end - self.start)
 
with timer() as t:
    print "Hello, World!"
    time.sleep(2)

or gist.

This entry was posted in python. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">