Timeit function

Here i present a little function (with an example below) to time some bunch of code using timeit.

# -*- coding: utf-8 *-*
import timeit


class Chronoit():
    """
    A little class to handle timeit output.
    The output is in seconds.
    """
    def __init__(self, main_statement, setup_statement, total_iterations):
        self.main_stmt = main_statement
        self.setup_stmt = setup_statement
        self.total_iter = total_iterations

        t = timeit.Timer(self.main_stmt, self.setup_stmt)
        self.show_results(t.timeit(number=self.total_iter))

    def show_results(self, time_elapsed):
        time_per_pass = time_elapsed / self.total_iter
        if time_per_pass > 60.0:
            minutes_per_pass = time_per_pass / 60.0
            secs_per_pass = time_per_pass % 60.0
            print "#" * 50
            print "Timing"
            print "setup stmt: \"" + self.setup_stmt.split("\n")[1] + " [...]\""
            print "main stmt: \"" + self.main_stmt.split("\n")[1] + " [...]\""

            print "\t total time: %d secs" % time_elapsed
            print "\t iterations: %d " % self.total_iter
            print '%.2f mins/pass %.2f secs/pass' % \
                      (minutes_per_pass, secs_per_pass)
        else:
            secs_per_pass = time_per_pass
            print "_" * 50
            print "Timing"
            print "setup stmt: \"" + self.setup_stmt.split("\n")[1] + " [...]\""
            print "main stmt: \"" + self.main_stmt.split("\n")[1] + " [...]\""

            print "\t total time: %d secs " % time_elapsed
            print "\t iterations: %d " % self.total_iter
            print '\t %.2f secs/pass' % secs_per_pass

        print "_" * 50

if __name__ == "__main__":
    MAX_ITERATIONS = 10
    N, M = 100, 1000
################################################################################

setup_stmt = \
"""
import numpy
matrix = numpy.random.randint(0,100,(%d * %d))
#""" % (N, M)

main_stmt = \
"""
for i in xrange(%d * %d):
    pixel = matrix[i]
    pixel = pixel * 20
    matrix[i] = pixel
#""" % (N, M)
t_obj = Chronoit(main_stmt, setup_stmt, MAX_ITERATIONS)

My intention also is to extend this idea making a class of it, and do some profilling.


Comments

Popular posts from this blog

Como configurar el control de directv para que funcione con el Tv

Las Tutucas y todo lo demás

Python Ipdb Cheatsheet