The functoolsmodule 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