Created
June 8, 2022 04:58
-
-
Save pijyoi/762147d465adc5cef8673d1e37ed5ae2 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 LineSegments: | |
def __init__(self, use_array): | |
self.use_array = use_array | |
self.alloc(0) | |
def alloc(self, size): | |
self.arr = np.empty((size, 4), dtype=np.float64) | |
if self.use_array: | |
self.objs = shiboken6.wrapInstance(self.arr.ctypes.data, QtCore.QLineF) | |
else: | |
self.objs = list(map(shiboken6.wrapInstance, | |
itertools.count(self.arr.ctypes.data, self.arr.strides[0]), | |
itertools.repeat(QtCore.QLineF, 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, 4), dtype=np.float64) | |
arr[:, 0] = x | |
arr[:, 1] = y | |
arr[:, 2] = x + 2 | |
arr[:, 3] = y + 2 | |
return arr | |
nsegs = 10_000 | |
size = 500 | |
nframes = 100 | |
pattern = generate_pattern(nsegs, size) | |
def run(use_array): | |
# generate lines once | |
segments = LineSegments(use_array) | |
lines, memory = segments.get(nsegs) | |
memory[:] = pattern | |
# draw multiple frames using the same lines 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 use_array: | |
try: | |
painter.drawLines(lines, nsegs) | |
except TypeError: | |
pass | |
else: | |
painter.drawLines(lines) | |
painter.end() | |
t1 = perf_counter() | |
return t1 - t0 | |
for use_array in [False, True]: | |
duration = run(use_array) | |
fps = int(nframes / duration) | |
print(f'{use_array=} {duration=:.3f} {fps=}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment