希望这有助于某人
发现这篇很棒的文章使用 Cython 使您的 Python 代码加速超过 30 倍
在通过摄像头的视频流中使用相同的阶乘计算,每帧计算两帧
视频python.py
import numpy as np
import cv2
import time
def function(number):
cap = cv2.VideoCapture(0)
increment = 0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
start_time = time.time()
y = 1
for i in range(1, number+1):
y *= i
increment+=1
if increment >2:
# print(time.time()-start_time)
print('Python increment ',increment)
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
return 0
Run Code Online (Sandbox Code Playgroud)
video_cython.pyx
import numpy as np
import cv2
import time
cpdef int function(int number):
cdef bint video_true = True
cap = cv2.VideoCapture(0)
cdef int y = 1
cdef int i
cdef int increment = 0
cdef int increment_times = 0
while(video_true):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
start_time = time.time()
for i in range(1, number+1):
y *= i
increment_times+=1
if increment_times > 2:
# print(time.time()-start_time)
print('Cython increment ',increment_times)
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
return 0
Run Code Online (Sandbox Code Playgroud)
设置文件
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('video_cython.pyx',compiler_directives={'language_level' : "3"}))
Run Code Online (Sandbox Code Playgroud)
然后运行
python setup.py build_ext --inplace
视频测试.py
import video_python
import video_cython
import time
number = 100000
start = time.time()
video_python.function(number)
end = time.time()
py_time = end - start
print("Python time = {}".format(py_time))
start = time.time()
video_cython.function(number)
end = time.time()
cy_time = end - start
print("Cython time = {}".format(cy_time))
print("Speedup = {}".format(py_time / cy_time))
Run Code Online (Sandbox Code Playgroud)
结果:
Python增量3
Python 时间 = 6.602917671203613
Cython 增量 3
Cython 时间 = 0.4903101921081543
加速 = 13.466817083311046
所以在循环中做任何与 python 相关的事情都可以提高速度
使用Cython
不会对这个问题产生重大影响。
要获取代码的配置文件/基准测试Pycharm
,IDE 有一个分析工具,或者您可以使用kernprof。
但是,作为测试,您可以将代码转换Cython
为以下代码或C
代码:
[笔记]:
此方法适用于Python3 ,但经过一些更改也可以应用于Python2.7 。我之前测试过。
[更新]:
您还可以使用PyInstaller和Nuitka来测试将代码转换为已编译可执行文件的另一种方法。
归档时间: |
|
查看次数: |
6169 次 |
最近记录: |