上后谈爱情

导航

 
#!/usr/bin/env python
# coding:utf-8
# 这里显示的2层嵌套
# 本程序开始对装饰器进行初步的理解,装饰器主要与闭包在一起使用
# 2层嵌套 + 3层嵌套

# 2层嵌套器中对于外部函数调用进行修改值-相当于建立一个模板形式
import time
import random
# def decorator(time(加上一个参数))相当于三层
def time_cost(f):
    def _f(length):  # 计算函数f其运行的时间
        start = time.clock()
        a = f(length)
        end = time.clock()
        print f.__name__,"run cost time is:" , end-start
        return a  # f.__name__ 表示对外部函数名字显示
    return _f
@ time_cost
# 装饰器中 list_comp等于于装饰器中f,在装饰器中运行f就相当于
# 运行外部函数list_comp,增加了其中功能
# 三层嵌套的结构中采用带参数结构,在第二层过程上加
def list_com(length):
    return [(x,y) for x in range(length) for y in range(length) if x*y>25]
@ time_cost
def for_loop(length):
    a = []
    for x in range(0, length):
        for y in range(0, length):
            if x*y > 25:
                a.append((x, y))
    return a
# 测试数据:
list_com(1000)
for_loop(1000)

三层嵌套:

#!/usr/bin/env python
# coding: utf-8
#copyRight by heibanke

import time
import random

def time_cost(runloops):
    def decorator(f):
        def _f(*arg, **kwarg):
            min_time = 1000
            avg_time = 0
            for i in range(runloops):
                start = time.clock()
                a=f(*arg,**kwarg)
                end = time.clock()
                if min_time>end-start:
                    min_time = end-start
                avg_time+=(end-start)
            print f.__name__,"best run cost time is ",min_time
            print f.__name__,"avg run cost time is ",float(avg_time)/runloops
            
            return a
        return _f
    return decorator


@time_cost(100) # 在其中加上参数
def list_comp(length):
    return [(x,y) for x in range(length) for y in range(length) if x*y > 25]


@time_cost(100)
def for_loop(length):
    a=[]
    for x in range(0,length):
        for y in range(0,length):
            if x*y>25:
                a.append((x,y)) 
    return a
   
if __name__ == '__main__':
        
    a=list_comp(100)
    print len(a)
    b=for_loop(100)
    print len(b)

 

posted on 2016-05-13 17:52  上后谈爱情  阅读(111)  评论(0编辑  收藏  举报