在python中将像素绘制到屏幕上最快/最好的方法是什么?我曾尝试使用pygame进行此操作,但在高分辨率(例如300x300)下运行缓慢。
这是我要测试的脚本:
import pygame
import sys
import time
import random
size = (300, 300)
screen = pygame.display.set_mode(size)
def draw():
for y in range(size[1]):
for x in range(size[0]):
rnd = random.randint(0, 255)
col = (rnd, rnd, rnd)
screen.fill(col, ((x, y), (1, 1)))
pygame.init()
avgfps = []
prevTime = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print(sum(avgfps)/len(avgfps))
pygame.quit()
sys.exit(0)
draw()
pygame.display.update()
e = time.perf_counter()
frametime = e - prevTime
prevTime = e
avgfps.append(1/frametime)
使用大约6.5fps,并替换draw()
以使用PixelArray,可以得到大约6.7fps
def draw():
pixels = pygame.PixelArray(screen)
for y in range(size[1]):
for x in range(size[0]):
rnd = random.randint(0, 255)
col = (rnd, rnd, rnd)
pixels[x, y] = col
pixels.close()