Python 学习入门(38)—— @functools模块

The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.


functools 源码路径及内置函数:



利用@functools对函数运行时间,进行计时

代码示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blog.ithomer.net

import time, functools

def timeit(func):
    @functools.wraps(func)
    def __do__(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print("%s usedtime: %ss" % (func.__name__, time.time() - start))
        return result
    return __do__

@timeit
def print_str(num):
    sum = 0
    for i in range(num):
        sum += i
    print sum

@timeit
def main():
    print("print_str(100)")
    print_str(100)
    
    print("print_str(10000)")
    print_str(10000)
    
    print("print_str(1000000)")
    print_str(1000000)

if __name__ == "__main__":  
    main()
运行结果:

print_str(100)
4950
print_str usedtime: 3.60012054443e-05s
print_str(10000)
49995000
print_str usedtime: 0.000550985336304s
print_str(1000000)
499999500000
print_str usedtime: 0.0614850521088s
main usedtime: 0.0623250007629s

说明:运行结果中的红色部分,都是运行计时的结果


示例2:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blog.ithomer.net

import time, functools

def functools_wrapper(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("call from functools_wrapper...")
        start = time.time()
        result = func(*args, **kwargs)
        print("%s usedtime: %ss" % (func.__name__, time.time() - start))
#         return func(*args, **kwargs)    
        return result
    return wrapper
    
@functools_wrapper
def functools_partial():
    print(int('10'))        # 10
    print(int('10', 2))     # 2

    int2 = functools.partial(int, base=2)
    print(int2('10'))       # 2
    print(int2('1010'))     # 10

    int2 = functools.partial(int, base=8)
    print(int2('10'))       # 8
    print(int2('1010'))     # 520
   
@functools_wrapper
def functools_reduce():
    array = [1, 2, 3, 4, 5, 6]
    result = reduce((lambda x,y:x*y), array)
    print("result = %d" % result)           # 720
    
    result = functools.reduce((lambda x,y:x*y), array)
    print("result = %d" % result)            # 720

def main():
    functools_partial()
    functools_reduce()

if __name__ == "__main__":  
    main()
运行结果:

call from functools_wrapper...
10
2
2
10
8
520
functools_partial usedtime: 2.00271606445e-05s
call from functools_wrapper...
result = 720
result = 720
functools_reduce usedtime: 1.21593475342e-05s


参考推荐:

Python的functools模块

Python的functools


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值