我正在创建一个程序(来测试一个理论),并且为了获得我需要的数据,我需要一个尽可能快地运行的程序。
这就是问题所在 - 我已经尽可能快地完成了它,但它仍然很慢。它占用了我计算机的少量 RAM 和 CPU 容量。我正在使用 PyCharm 2017 Community Edition 运行该程序。
代码如下;我将如何进一步优化或更改它以使其运行得更快?
主要内容:
from functions import *
from graphics import *
import time
Alpha = True
x = timestamp()
while Alpha:
master = GraphWin(title="Image", width=512, height=512)
build_image(master)
getter(master, x)
x = timestamp()
time.sleep(3)
master.close()
模块“功能”:
from graphics import *
import random
from PIL import ImageGrab
def build_image(window):
for i in range(513):
for j in range(513):
fig = Rectangle(Point(j, i), Point(j + 1, i + 1))
color = random.randrange(256)
fig.setFill(color_rgb(color, color, color))
fig.setOutline(color_rgb(color, color, color))
fig.draw(window)
def getter(widget, counter):
x = widget.winfo_rootx()+widget.winfo_x()
y = widget.winfo_rooty()+widget.winfo_y()
x1 = x+widget.winfo_width()
y1 = y+widget.winfo_height()
ImageGrab.grab().crop((x, y, x1, y1)).save("{}.png".format(str(counter)))
def timestamp():
timelist = time.gmtime()
filename = ("Image" + "_" + str(timelist[0]) + "_" + str(timelist[1]) + "_" + str(timelist[2]) + "_" +
str(timelist[3]) + "_" + str(timelist[4]) + "_" + str(timelist[5]) + "_UTC")
return filename
注意:“图形”模块是一个允许轻松操作 Tkinter 的模块。
请您参考如下方法:
您的速度缓慢可能是因为您将像素视为窗口中的矩形。
如果您只想生成随机图像,则可以跳过窗口部分。在没有太多回避之后,我发现了这段代码:
from PIL import Image
import random
def drawImage():
testImage = Image.new("RGB", (600,600), (255,255,255))
pixel = testImage.load()
for x in range(600):
for y in range(600):
red = random.randrange(0,255)
blue = random.randrange(0,255)
green = random.randrange(0,255)
pixel[x,y]=(red,blue,green)
return testImage
def main():
finalImage = drawImage()
finalImage.save("finalImage.jpg")
