python高性能编程——案例1

CPU密集型函数代码示例:

import time
import functools
x1,x2,y1,y2 = -1.8,1.8,-1.8,1.8
c_real,c_imag = -0.62772,-.42193
def calc_pure_python(desired_width,max_iterations):
    x_step = (float(x2-x1)/float(desired_width))
    y_step = (float(y1-y2)/float(desired_width))
    x=[]
    y=[]
    ycoord = y2
    while ycoord>y1:
        y.append(ycoord)
        ycoord+=y_step
    xcoord = x1
    while xcoord<x2:
        x.append(xcoord)
        xcoord+=x_step
    zs = []
    cs=[]
    for ycoord in y:
        for xcoord in x:
            zs.append(complex(xcoord,ycoord))
            cs.append(complex(c_real,c_imag))
    print("x的长度为:"+str(len(x)))
    print("总共的元素个数为:"+str(len(zs)))
    start_time = time.time()
    output = calculate_z_serial_purepython(max_iterations,zs,cs)
    end_time = time.time()
    secs = end_time-start_time
    print("花费的时间为:"+str(secs))
    assert sum(output)==33219980

def calculate_z_serial_purepython(maxiter,zs,cs):
    output = [0]*len(zs)
    for i in range(len(zs)):
        n=0
        z = zs[i]
        c = cs[i]
        while abs(z)<2 and n<maxiter:
            z = z*z+c
            n+=1
        output[i]=n
    return output

if __name__ == '__main__':
    calc_pure_python(desired_width=1000,max_iterations=300)

简单的计时方法——使用修饰器!

注意

1、原本书上的内容存在出入,目前的wraps在functools包内,因此需要首先音容functools包!

2、打印函数的名称时,在python3中现在的方法已经将func_name属性改成了__name__.

import functools
def timefn(fn):
    @functools.wraps(fn)
    def mesure_time(*args,**kwargs):
        t1 = time.time()
        result = fn(*args,**kwargs)
        t2 = time.time()
        print("@timefn:"+fn.__name__+" took "+str(t2-t1)+" senconds")
        return result
    return mesure_time

@timefn
def calc_pure_python(desired_width,max_iterations):
......

分析:

1、从最外层看,是一个timefn函数,然后这个函数以一个新的函数fn作为参数

2、内嵌函数mesure_time,这个函数的参数*args表示数量可变的位置函数,**kwargs表示数量可变的键值对参数

3、在mesure_time函数内部,把接受到的参数传入fn函数

4、t1记录执行fn函数之前的时间,t2表示执行fn函数之后的时间,最后使用fn.__name__打印函数的名称,使用t2-t1打印出花费的时间

知识点:

@functools.wraps修饰的作用是:在不影响装饰器使用的情况下,可以直接使用被调用函数的内置功能,理解起来有些抽象,具体的含义是当使用@修饰符修饰函数时,会存在这样一个问题:被修饰的函数会消失(这是因为修饰函数没有设置返回值,如果设置了返回值,则就把返回值赋给被修饰函数。

目前理解不深,先记录下。

注意:使用额外的分析信息会降低代码的执行速度!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值