python自学

python提升执行速度的几种方式

2019-09-25  本文已影响0人  数据小菜鸟
  1. pypy 不需要修改代码 直接执行
  2. numba 安装 修改少数代码可以得到大幅提升
  3. Cython 需要编译成c语言同时有加密代码作用
#!/usr/bin/env python
#-*-coding:utf-8-*-

#原版代码 
import time
import pandas as pd

def time_com(i):
    cum = 0
    for test in range(i):
        for ind in range(i):
            cum += (test * ind) % 3
 
if __name__ == '__main__':
    t1 = time.clock()
    df = pd.DataFrame()
    for i in range(500):
        time_com(i)
    t2 = time.clock()
    print "run time:%f s" % (t2 - t1)
#!/usr/bin/env python
#-*-coding:utf-8-*-

# 使用numba 加速代码 
import time
import pandas as pd
from numba import jit


@jit
def time_com(i):
    cum = 0
    for test in range(i):
        for ind in range(i):
            cum += (test * ind) % 3
 
if __name__ == '__main__':
    t1 = time.clock()
    df = pd.DataFrame()
    for i in range(500):
        time_com(i)
    t2 = time.clock()
    print "run time:%f s" % (t2 - t1)
上一篇下一篇

猜你喜欢

热点阅读