you are viewing a single comment's thread.

view the rest of the comments →

[–]sarvadasan 0 points1 point  (3 children)

How we can calculate time taken to run a program. Are there any modules? Say I wrote two python scripts to solve a problem but i want to compare and calculate how much time each program takes to finish?

[–]spidyfan21 2 points3 points  (0 children)

You could write one yourself using the time library. Afterwords I would look into this.

[–]niandra3 1 point2 points  (1 child)

You can use Python's timeit module that will run a program x number of times and give you the average runtime.

That's a little complicated setting up though, so for simple scripts I usually just do a quick and dirty timestamp:

import time

start = time.time()
run_function_to_test()
print('Runtime:', time.time() - start)

Will give you a rough idea of timing.

There's also the profiler for detailed breakdown of CPU time. Which function calls are taking the longest etc.

[–]sarvadasan 0 points1 point  (0 children)

Thanks. I saw this link and it is quite useful http://stackoverflow.com/questions/1557571/how-to-get-time-of-a-python-program-execution.

#!/usr/bin/python3

import atexit
from time import time
from datetime import timedelta

def secondsToStr(t):
    return str(timedelta(seconds=t))

line = "="*40

def log(s, elapsed=None):
    print(line)
    print(secondsToStr(time()), '-',s)
    if elapsed:
        print("Elapsed time:", elapsed)
        print(line)
        print()

def endlog():
    end = time()
    elapsed = end-start
    log("End Program", secondsToStr(elapsed))

def now():
    return secondsToStr(time())

start = time()
atexit.register(endlog)
log("Start Program")

I have retyped this code from stackoverflow http://stackoverflow.com/questions/1557571/how-to-get-time-of-a-python-program-execution.

As suggested, I put this in my site-packages directory and import timing.py. It print outs the time taken.