0

every time i run this code i get time 0.0, but i want exact time took by the function to run, i tried by increasing the values of arguments. pls help mi !!

import time
from functools import wraps

def calculate_time(function):
    @wraps(function)
    def wrapper(*args, **kwargs):
        print(f"you are calling {function.__name__} function")
        print(f"{function.__doc__}")
        t1 = time.time()
        returned_func = function(*args, **kwargs)
        t2 = time.time()
        total_time = t2 -t1
        print(f"this function took {total_time} seconds")
        return returned_func
    return wrapper

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 101, 11, 12, 12, 1000000]

@calculate_time
def squares(n):
    '''this function returns the squares of numbers'''
    return [i**2 for i in range(1, n+1)]

squares(1000)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Note that `nums` is unused – wjandrea Jun 06 '20 at 18:01
  • 1
    It works fine for me - took about 0.0004 seconds. Maybe try increasing `n` up to 10000000, then it will take on the order of seconds. What platform are you using? – wjandrea Jun 06 '20 at 18:04
  • Related? [How can I time a code segment for testing performance with Pythons timeit?](https://stackoverflow.com/q/2866380/4518341) It goes over some pitfalls of different timing methods, e.g. `time.time()` is not precise enough on Windows. – wjandrea Jun 06 '20 at 18:07

2 Answers2

0

This worked fine for me:

>>> ret = squares(1000)
you are calling squares function
this function returns the squares of numbers
this function took 0.0009975433349609375 seconds
>>> ret = squares(1000000)
you are calling squares function
this function returns the squares of numbers
this function took 0.21860361099243164 seconds
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

looks like it worked

printed

you are calling squares function
this function returns the squares of numbers
this function took 0.000997304916381836 seconds
wjandrea
  • 28,235
  • 9
  • 60
  • 81
john taylor
  • 1,080
  • 15
  • 31