How to use computer language slowly 2
There are many ways to slow down your computer. -Do not make unnecessary copies when dealing with subarrays. When the processing language / library supports the concise notation of the sub-array, instead of making a copy of the sub-array, the sub-array itself should be used as an argument of the function.
Here's an example of Python numpy. as follows B = A [3: 6] does not make a copy, it is just an alias for the subarray. It's an alias, so if you change the element in B, it's also changed for the original array.
C = A [3: 6] +0 makes a copy. Therefore, changing the copy does not change the original array. If you didn't know this difference, you would say, "I intended to change the copy, but the original array has changed." It will cause errors that are common to beginners.
>>> import numpy as np >>> A=np.arange(0,10,1) >>> A array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> A[3:6] array([3, 4, 5]) \ >>>> B = A [3: 6] # This does not make a copy >>> B[0]=-3 >>> A array([ 0, 1, 2, -3, 4, 5, 6, 7, 8, 9]) \ >>>> C = A [3: 6] +0 # This makes a copy >>> C array([-3, 4, 5]) >>> C[0]=-30 >>> A array([ 0, 1, 2, -3, 4, 5, 6, 7, 8, 9]) >>>
It's also faster if you replace the assignment with an in-situ assignment. Consider using * =, + =,-=, etc.
inplace.py
# -*- coding: utf-8 -*-
import cv2
import numpy as np
e0 = cv2.getTickCount()
a = np.ones((1024, 1024))
for i in range(20):
a = a*2
print np.sum(a[:])
e1 = cv2.getTickCount()
a = np.ones((1024, 1024))
for i in range(20):
a *= 2
print np.sum(a[:])
e2 = cv2.getTickCount()
print (e1 - e0) / cv2.getTickFrequency(), "# a = a*2"
print (e2 - e1) / cv2.getTickFrequency(), "# a *= 2"
print (e2 - e1) / (e1 - e0)
Execution result 1.09951162778e+12 1.09951162778e+12 0.116400550283 # a = a*2 0.0270198481919 # a *= 2 0.23212818261
The processing time has been reduced to 23% (4 times faster).
** Summary ** ・ Do not make a copy in the partial array ・ Do not use "* =" when "* =" is sufficient.
For Python, "High Performance Python" You should read.
Recommended Posts