我創建一個程序(測試理論),並獲得我所需要的數據,我需要一個程序,以儘可能快地運行。Python的速度優化
這裏的問題 - 我已和我一樣快可以管理,它仍然是慢。它使用我的電腦的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的操控方便。
PyCharm只是要使用它配置使用的W/E Python解釋器。如果你的程序運行的話,它不會有太多的影響。這是一個非常模糊的問題。使用一個分析器來找出什麼是最花時間和優化。根據您的限制,您可能需要更快(非解釋)的語言。 –
望着[文件](http://pillow.readthedocs.io/en/3.1.x/reference/ImageGrab.html)我發現,你能傳遞'bbox'參數PIL.ImageGrab.grab。這可以節省一些時間。您也可以考慮使用PIL來首先創建您的圖像,而不是像奧斯汀黑斯廷斯建議的那樣拍攝窗口截圖。 – BurningKarl
@CDspace回滾您的編輯。這個問題已經解決了,請不要改變它。 –