Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to use timeit?

Tags:

python

timeit

I tried to make decorator for method that can count run time of another function in Python

def timer(func):
        def smallfunctimer(*args,**kwargs):
            res=func(*args,**kwargs)
            tm=timeit.Timer(lambda:res)
            print("Function time: ", tm)
        return smallfunctimer

@timer
    def deposit(self,amount):
        self.balance+=amount
        self.queue.append(BankTransaction(amount))

but when i call it

ba=BankAccount(1,100)
ba.deposit(10000000)

i get this:

Function time:  <timeit.Timer object at 0x0281D370>

How may i get run time in seconds?

like image 827
Igor Achmiz Avatar asked Jul 18 '26 20:07

Igor Achmiz


1 Answers

You created a timeit.Timer() instance; you'd need to call a method on that instance for it to actually run the code:

print("Function time: ", tm.timeit(1000))

would give you the time it took to run the function 1000 times.

like image 102
Martijn Pieters Avatar answered Jul 21 '26 10:07

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!