首页 > 解决方案 > Fastest way to draw pixels to screen in python

问题描述

What is the fastest / best way to draw pixels to a screen in python? I have tried doing it with pygame but it is slow at high resolutions (such as 300x300).

Here's the script I'm using to test:

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)

Using that I get about 6.5fps, and by replacing draw() to use PixelArray I get about 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()

标签: python

解决方案


推荐阅读