S
S
Sergey Kolesnik2021-08-13 12:21:31
Python
Sergey Kolesnik, 2021-08-13 12:21:31

When using range( ), does the speed drop after N-th number of cycles?

When using range( ), after the Nth number of cycles, the speed drops. I didn’t find a solution on the Internet as such (well, or it was written in an inaccessible language that I just didn’t understand) I’m attaching the code below.

from graphics import *


win = GraphWin("Окно для графики", 310, 350)
win.setBackground('white')

def down():
        for i in range(250):
            print (i)
            obj = Circle(Point(150, 20), 15)
            
            obj.move(0, i)
            obj.setFill("yellow")
            obj.setWidth(1)
            obj.draw(win)
            
            
def up():   
            
        for i in reversed(range(250)):
                print (i)

                obj = Circle(Point(150, 20), 15)

                obj.move(0, i)
                obj.setWidth(1)
                obj.setFill("red")
                obj.draw(win)


while True:
        down()
        up()
                
win.getMouse()
win.close()

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
o5a, 2021-08-13
@Sergey_418

Because in general the approach is wrong. You create a new object every cycle and simply draw it on top of the others, shifting each time by a new amount.
Instead, you need to create your own Circle once and only then move it (and move accordingly not by i, but by the same fixed value (if uniform movement is expected).
And probably it is worth adding a delay in the form of time.sleep(0.01) to the loop

obj = Circle(Point(150, 20), 15)
obj.setWidth(1)
obj.draw(win)

def down():
    for i in range(250):
        print (i)

        obj.setFill("yellow")
        obj.move(0, 1)
        time.sleep(0.01)

V
Vindicar, 2021-08-13
@Vindicar

reversed(range(250))
Why? Why didn't range(249, -1, -1) work?
Further, you create the same object over and over again in up() and down() in a loop, and then you forget about it. Why warm up the garbage collector? Create an object once and modify it - either in a global variable or (better) in a class.

L
LXSTVAYNE, 2021-08-13
@lxstvayne

Prints noticeably slow down the program, try without them ;) And indeed, you can not recreate some variables, I'm not talking about the generator. You can create your Circle object in a loop, and pass it to the up and down functions and change it, rather than creating it every time - an expensive operation, however.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question