Last active
June 9, 2022 04:37
-
-
Save pijyoi/5ddb551aa42b60eee49b52d8e3a3e5f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from PySide6 import QtCore, QtGui | |
import shiboken6 | |
import numpy as np | |
import itertools | |
from time import perf_counter | |
class Points: | |
def __init__(self, use_array): | |
self.use_array = use_array | |
self.alloc(0) | |
def alloc(self, size): | |
self.arr = np.empty((size, 2), dtype=np.float64) | |
if self.use_array: | |
self.objs = shiboken6.wrapInstance(self.arr.ctypes.data, QtCore.QPointF) | |
else: | |
self.objs = list(map(shiboken6.wrapInstance, | |
itertools.count(self.arr.ctypes.data, self.arr.strides[0]), | |
itertools.repeat(QtCore.QPointF, self.arr.shape[0]))) | |
def get(self, size): | |
if size != self.arr.shape[0]: | |
self.alloc(size) | |
return self.objs, self.arr | |
def generate_pattern(nsegs, size): | |
rng = np.random.default_rng() | |
x = rng.random(nsegs) * size | |
y = rng.random(nsegs) * size | |
arr = np.empty((nsegs, 2), dtype=np.float64) | |
arr[:, 0] = x | |
arr[:, 1] = y | |
return arr | |
nsegs = 10_000 | |
size = 500 | |
nframes = 100 | |
pattern = generate_pattern(nsegs, size) | |
def run(mode): | |
# generate points once | |
if mode in ['array', 'list']: | |
segments = Points(use_array = mode == 'array') | |
points, memory = segments.get(nsegs) | |
memory[:] = pattern | |
else: | |
x, y = pattern[:, 0].copy(), pattern[:, 1].copy() | |
# draw multiple frames using the same points array | |
t0 = perf_counter() | |
for _ in range(nframes): | |
qimg = QtGui.QImage(size, size, QtGui.QImage.Format.Format_RGB32) | |
qimg.fill(QtCore.Qt.GlobalColor.transparent) | |
painter = QtGui.QPainter(qimg) | |
painter.setPen(QtCore.Qt.GlobalColor.cyan) | |
if mode == 'array': | |
painter.drawPoints(points, nsegs) | |
elif mode == 'numpy': | |
painter.drawPointsNp(x, y) | |
else: | |
painter.drawPoints(points) | |
painter.end() | |
t1 = perf_counter() | |
return t1 - t0 | |
for mode in ['list', 'array', 'numpy']: | |
duration = run(mode) | |
fps = int(nframes / duration) | |
print(f'{mode=} {duration=:.3f} {fps=}'), |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment