zoukankan      html  css  js  c++  java
  • Python_Tips[7] -> 偏函数

    偏函数 / Partial Function


    使用偏函数可以对函数的部分预先知道的参数进行冻结,从而缓存函数参数,而在运行时再释放参数进行使用。所以偏函数适用于需要多次调用同样一个函数且其中一个参数固定已知的情况下。

    偏函数的使用方式主要如下,

     1 import time
     2 from functools import partial as pto
     3 
     4 
     5 def add(a, b):
     6     return a+b
     7 
     8 pto_add = pto(add, 1)
     9 
    10 print(add(1, 2))
    11 print(pto_add(2))

    可以看到,利用偏函数可以生成一个新的函数类,这点在GUI编程中可以得到很好的利用,例如一个Dialog类,可以通过传入不同固定参数得到不同类型的偏函数,从而免去多个函数的定义。

    而至于偏函数的性能,则使用下面的方式进行一个简单的测试,分别以原始函数和偏函数进行10^7次计算,并重复3次得到计算消耗的平均时间。

     1 def test_1(x):
     2     start = time.time()
     3     for i in range(10**7):
     4         x(1, i)
     5     end = time.time()
     6     return end-start
     7 
     8 def test_2(x):
     9     start = time.time()
    10     for i in range(10**7):
    11         pto_add(i)
    12     end = time.time()
    13     return end-start
    14 
    15 print(sum(test_1(add) for i in range(3))/3) # 1.6598326365152996
    16 print(sum(test_2(pto_add) for i in range(3))/3) # 2.585925261179606

    最后得到结果发现,偏函数计算的平均时间消耗比直接调用更大。

  • 相关阅读:
    Sum Root to Leaf Numbers
    Sum Root to Leaf Numbers
    Sort Colors
    Partition List
    Binary Tree Inorder Traversal
    Binary Tree Postorder Traversal
    Remove Duplicates from Sorted List II
    Remove Duplicates from Sorted List
    Search a 2D Matrix
    leetcode221
  • 原文地址:https://www.cnblogs.com/stacklike/p/8379190.html
Copyright © 2011-2022 走看看