python 核心编程第十一章 13题

来源:互联网 发布:什么是硬件软件 编辑:程序博客网 时间:2024/06/05 19:14

分别用不同的方法去实现阶乘,并且用装饰器去计算不同的阶乘的时间,实现很简单,就是装饰器那里有点模糊,装饰函数里面一定要返回装饰器内嵌函数的函数对象。还ti有一点就是time.clock()和time.time()表示什么,C里面clock表示cpu的时钟数,然后通过CLOCKS_PER_SEC计算时间,而python里面貌似没有这么个data,clock表示什么呢,不懂,求解。。

#!/usr/bin/pythonimport timedef mul(x,y):return x*ydef timeit(func):def counter(*data):start = time.time()result = func(*data)end = time.time()print '-'*20print 'result is %d' % result print "function %s consuming time is %f\n" %(func.__name__,end -start)return resultreturn counter@timeitdef jiecheng_01(n):return reduce(mul,range(1,n+1))@timeitdef jiecheng_02(n):return reduce(lambda x,y:x*y ,range(1,n+1))@timeitdef jiecheng_03(n):if n==1:return 1else:return n*jiecheng_03(n-1)if __name__ == '__main__':funcs = [jiecheng_01,jiecheng_02,jiecheng_03]for func  in funcs:func(30)


原创粉丝点击