N
N
Name_Zagotovka2021-05-11 09:46:56
Python
Name_Zagotovka, 2021-05-11 09:46:56

Python - how to lighten a python script?

There is a crypt whose work is as follows.
I made a screenshot of the screen,
cut the screen, if necessary,
compared it with the sample (the sample is saved to disk)
, when the result is obtained, press the buttons.
we have the following code

from PIL import ImageGrab
from cv2 import matchTemplate,minMaxLoc,imread,cvtColor,COLOR_RGB2BGR,TM_CCOEFF_NORMED
from numpy import array
from pyautogui import moveTo,click,keyDown,keyUp,press
from time import sleep,time
from random import choice
#таких функций около 8
def chek_some(all_img):
    koof=0.9
    img=all_img.crop(какаято область)
    img=cvtColor(array(img), COLOR_RGB2BGR)
        res = matchTemplate(img,какойто изображение,TM_CCOEFF_NORMED)
        min_v, max_v, min_pt, max_pt = minMaxLoc(res)
        if max_v>=koof:
            stat=True
            break
        else:
            stat=False
    return(stat)
#таких функций около 6	
def do_some(some_stat):
    
    click(some_stat)
    sleep(0.2)
    some_stat+=20
    click(some_stat)
    
def main():
    #в данной функции описано порядок выполениня функций chek и do
  all_img=ImageGrab.grab()
  some_stat1=chek_some1(all_img)
  some_stat2=chek_some2(all_img)
  some_stat3=chek_some3(all_img)
  some_stat4=chek_some4(all_img)
  if some_stat1:
    do_some1(some_stat1):
    elif some_stat2:
        do_some2(some_stat2)
    elif some_stat2 and some_stat3:
        do_some3(some_stat3)
while True:
    main()


At the same time, at startup, the entire script loads the CPU by 25 percent (provided that the program itself, from which we read the image, takes no more than 10 percent of the CPU).
Question:
How is it possible to reduce the load on the CPU, if it is possible with such a task at all ...
PS in the example there may have been syntactic / logical errors (

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-11-03
@chainikk

The longpoll variable was not declared anywhere

longpoll = VkLongPoll(vk_session)
for event in longpoll.listen():

S
Sergey Pankov, 2021-05-11
@Name_Zagotovka

The problem is that the delay here is only in do_some *, and in other cases, your script takes screenshots, crops and compares pictures as fast as possible. That is, the program is written in such a way that it must and will completely utilize the entire kernel with its process. As I understand it, you have a four-core percent, hence 25 percent.
Add a delay to the main check loop and you'll take a lot of load off your CPU.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question