1. 程式人生 > 其它 >python中的效能優化的裝飾器

python中的效能優化的裝飾器

技術標籤:python

  • LRU lru_cache Least Recently Used 是快取置換中的一種常用演算法,從原始碼中看

  • If maxsize is set to None, the LRU features are disabled and the cache
    can grow without bound.

  • If typed is True, arguments of different types will be cached separately.
    For example, f(3.0) and f(3) will be treated as distinct calls with

    distinct results.

    • 該裝飾器有兩個引數,一個是可以快取的最大次數maxsize,
    • 一個是typed ,如果該引數是True,不同型別的引數分別快取。如果為False,之快取一次。
    • 這個裝飾可以用來優化遞迴演算法,效能很明顯。
    • 程式碼如下:
      from timeit import Timer
      from functools import lru_cache
      import sys
      sys.setrecursionlimit(2000) # 設定最大遞迴深度
      
      @lru_cache(128) # 128 快取的最大次數,如果沒有,為無窮大
      def fibo(n):
          if n == 1 or n ==
      2: return 1 return fibo(n - 1) + fibo(n - 2) def sum(): total = 0 for i in range(1,20+1): total+=fibo(i) return total t1=Timer("sum()","from __main__ import sum") print("cost time:%s"%(t1.timeit(1000))) # 計算1000 次的平均耗時
  • 使用 Timer 來計算程式碼執行的時間,計算斐波那契數列的前20項和。

  • 不適用快取裝飾器的話耗時:

  • 在這裡插入圖片描述耗時6秒,而且計算前50項的時候,我的電腦已經計算不出來。

  • 而使用快取裝飾用時如圖:

  • 在這裡插入圖片描述相差了將近1000倍。

  • 而且可以計算斐波那契數列的前1000項和的值

  • 在這裡插入圖片描述
    耗時0.9s ,效能提升有很明顯的優勢