Skip to content

Instantly share code, notes, and snippets.

@rexlow
Created January 3, 2019 08:55
Show Gist options
  • Save rexlow/49ab42b921b59cfd7229e410b5db32b9 to your computer and use it in GitHub Desktop.
Save rexlow/49ab42b921b59cfd7229e410b5db32b9 to your computer and use it in GitHub Desktop.
NumpyPerformanceTest
""" File name : NumpyPerformanceTest.py
Description : This script is to profile the performance of different numpy methods
Usage : python3 NumpyPerformanceTest.py
Author : Rex Low
"""
import cv2
import numpy as np
from time import time
np.random.seed(0)
green = [0,255,0]
blue = [255,0,0]
red = [0,0,255]
white = [255,255,255]
black = [0,0,0]
def np_simple():
x = np.random.randint(0, 5, (500,500))
row, col = x.shape
y = np.zeros((row, col, 3), np.uint8)
start = time()
for i in range(row):
for j in range(col):
k = x[i][j]
if k == 0:
y[i][j] = green
elif k == 1:
y[i][j] = blue
elif k == 2:
y[i][j] = red
elif k == 3:
y[i][j] = white
elif k == 4:
y[i][j] = black
return time() - start
def np_item():
x = np.random.randint(0, 5, (500,500))
row, col = x.shape
y = np.zeros((row, col, 3), np.uint8)
start = time()
for i in range(row):
for j in range(col):
k = x.item(i, j)
if k == 0:
y.itemset((i, j, 0), green[0])
y.itemset((i, j, 1), green[1])
y.itemset((i, j, 2), green[2])
elif k == 1:
y.itemset((i, j, 0), blue[0])
y.itemset((i, j, 1), blue[1])
y.itemset((i, j, 2), blue[2])
elif k == 2:
y.itemset((i, j, 0), red[0])
y.itemset((i, j, 1), red[1])
y.itemset((i, j, 2), red[2])
elif k == 3:
y.itemset((i, j, 0), white[0])
y.itemset((i, j, 1), white[1])
y.itemset((i, j, 2), white[2])
elif k == 4:
y.itemset((i, j, 0), black[0])
y.itemset((i, j, 1), black[1])
y.itemset((i, j, 2), black[2])
return time() - start
def np_palette():
start = time()
x = np.random.randint(0, 5, (500,500))
color = np.array([green, blue, red, white, black], np.uint8)
y = color[x]
return time() - start
if __name__ == "__main__":
iterations = 10
np_simple_test = np.mean([np_simple() for _ in range(iterations)])
np_item_test = np.mean([np_item() for _ in range(iterations)])
np_palette_test = np.mean([np_palette() for _ in range(iterations)])
print("Time taken for different methods")
print("NP Simple : {:.5f}s".format(np_simple_test))
print("NP Item : {:.5f}s".format(np_item_test))
print("NP Palette : {:.5f}s".format(np_palette_test))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment