讓Python的執行速度變快,有以下幾種作法:
什麼都不用改,就能節省至少50%時間!
conda install -c anaconda cython
或使用pip
pip install cython
def test(x):
y = 0
for i in range(x):
y = y + i
return y
def prime(givenNumber):
primes = []
for possiblePrime in range(2, givenNumber + 1):
isPrime = 1
for num in range(2, possiblePrime):
if possiblePrime % num == 0:
isPrime = 0
if isPrime:
primes.append(possiblePrime)
return primes
cpdef double test(int x):
cdef double y = 0
cdef double i
for i in range(x):
y = y + i
return y
# 與method_old.py一模一樣
def prime1(givenNumber):
primes = []
for possiblePrime in range(2, givenNumber + 1):
isPrime = 1
for num in range(2, possiblePrime):
if possiblePrime % num == 0:
isPrime = 0
if isPrime:
primes.append(possiblePrime)
return primes
# 有加入宣告
cpdef list prime2(int givenNumber):
cdef list primes = []
cdef unsigned int possiblePrime
cdef unsigned int num
cdef int isPrime
for possiblePrime in range(2, givenNumber + 1):
isPrime = 1
for num in range(2, possiblePrime):
if possiblePrime % num == 0:
isPrime = 0
if isPrime:
primes.append(possiblePrime)
return primes
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("method_new.pyx")
)
python setup.py build_ext --inplace
>> 正在產生程式碼
>> 已完成程式碼產生
會產生 .c 和 .pyd 檔,後者是主要用來執行的binary檔import method_old as old
import method_new as new
import time
print(old.test(50000000))
print(new.test(50000000))
start = time.time()
old.prime(50000)
print('Old:', '%.2f'%(time.time() - start), 'sec')
start = time.time()
new.prime1(50000)
print('Cython1:', '%.2f'%(time.time() - start), 'sec')
start = time.time()
new.prime2(50000)
print('Cython2:', '%.2f'%(time.time() - start), 'sec')
執行結果與時間:
1249999975000000
1249999975000000.0
Old: 82.44 sec
Cython1: 46.82 sec
Cython2: 2.98 sec
test()累加0~50000000都是一樣結果歡迎大家在底下留言:你執行後出現的秒數為何?
cython -a method_new.pyx
會產生method_new.html