希望这对某人有所帮助
发现这篇很棒的帖子Use Cython to get more than 30X speedup on your Python code
在通过相机的视频流中使用相同的阶乘计算,每帧两帧
video_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
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
setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('video_cython.pyx',compiler_directives={'language_level' : "3"}))
然后运行
python setup.py build_ext --inplace
video_test.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))
结果:
Python 增量 3
Python 时间 = 6.602917671203613
Cython 增量 3
Cython 时间 = 0.4903101921081543
加速 = 13.466817083311046
所以在循环中做任何与 python 相关的事情都可以提高速度