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 source code path and built-in functions:
Use @ functools to time the function running time
Sample Code: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vc3ryb25np1_vcd48cd48l3a + PHByZSBjbGFzcz0 = "brush: java;"> #! /Usr/bin/env python #-*-coding: UTF-8-*-# blog. ithomer. netimport time, functoolsdef 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 __@ timeitdef print_str (num): sum = 0 for I in range (num ): sum + = I print sum @ timeitdef 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 ()Running result:
Print_str (100)
4950
Print_str usedtime: 3.60012054443e-05 s
Print_str (10000)
49995000
Print_str usedtime: 0.000550985336304 s
Print_str (1000000)
499999500000
Print_str usedtime: 0.0614850521088 s
Main usedtime: 0.0623250007629 s
Note: The red part of the running result is the result of running timing.
Example 2:
#!/usr/bin/env python# -*- coding: utf-8 -*-# blog.ithomer.netimport time, functoolsdef 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_wrapperdef 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_wrapperdef 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) # 720def main(): functools_partial() functools_reduce()if __name__ == "__main__": main()
Running result:Call from functools_wrapper...
10
2
2
10
8
520
Functools_partial usedtime: 2.00271606445e-05 s
Call from functools_wrapper...
Result = 720.
Result = 720.
Functools_reduce usedtime: 1.21593475342e-05 s
Reference recommendations:
Python functools Module
Python functools