Monday, August 23, 2021

how to use timer to debug the performance issue in python?

 it is very common to encounter the performance issue. it is very easy to identfiy the function with such issue by adding the timer inside the function or put the timer before and after the function call.

here is a sample snippet to show how to use the time to track the function execution

import time

# @cache
def fib(n):
    if n<=1:
        return n
    else:
        return fib(n-1) +fib(n-2)

def main():
    start=time.perf_counter()
    for i in range(40):
        print(ifib(i))
    print("done")
    elapsed= time.perf_counter() -start
    print(f"completed in {elapsed} seconds")
        

if __name__ == '__main__':
    main()

the output is showing that the function was completed in 69.8057579 seconds.  it indicated that we should opitmize this function for better performance.


PS C:\code\python\python> & C:/Python39/python.exe c:/code/python/python/tutorial/cache/fibonacci_sequnce.py

0 0

1 1

2 1

3 2

4 3

5 5

6 8

7 13

8 21

9 34

10 55

11 89

12 144

13 233

14 377

15 610

16 987

17 1597

18 2584

19 4181

20 6765

21 10946

22 17711

23 28657

24 46368

25 75025

26 121393

27 196418

28 317811

29 514229

30 832040

31 1346269

32 2178309

33 3524578

34 5702887

35 9227465

36 14930352

37 24157817

38 39088169

39 63245986

done

completed in 69.8057579 seconds

PS C:\code\python\python>

how can we improve the performance of this function? Cache will dramatically improve the execution time.

here is the improved version 

from functools import cache
import time

@cache
def fib(n):
    if n<=1:
        return n
    else:
        return fib(n-1) +fib(n-2)

def main():
    start=time.perf_counter()
    for i in range(40):
        print(ifib(i))
    print("done")
    elapsed= time.perf_counter() -start
    print(f"completed in {elapsed} seconds")
        

if __name__ == '__main__':
    main()

done

completed in 0.0112849 seconds

the execution time is less than 1 seocond which is huge change comparing to the previous function will cost 89 second to complete.







No comments:

Post a Comment