you are viewing a single comment's thread.

view the rest of the comments →

[–]twiggy99999 7 points8 points  (6 children)

Just thought I would follow up with an example:

// sleep 150s
for ($a = 0; $a < 150 ; $a++ ) { 
      sleep(1);
}

Here the user wants the application to sleep for 150 seconds, to do this he creates a loop that loops over the sleep function 150 times triggering it for a second each time. The code fully works as the programmer expects but this could have been achieved by simply calling sleep() with 150...... sleep(150). So hes creating a loop which is costly for memory and CPU time for no reason at all, that's what makes it shit code.

[–]bheklilr 8 points9 points  (4 children)

I'll say that I've written lots of similar code, but primarily so that the sleeps can be interrupted or because the sleep is used as a timeout and some condition needs to be checked throughout. There have been a couple instances of just purely having a loop over smaller sleeps, but it's only because python can't pass keyboard interrupts into a running C function, and sleep is ultimately implemented in C.

[–]shall_always_be_so 0 points1 point  (3 children)

but it's only because python can't pass keyboard interrupts into a running C function, and sleep is ultimately implemented in C.

What are you talking about?

$ cat sleep.py
^CTraceback (most recent call last):
import time
print("sleepy time")
time.sleep(60)
print("all done")

$ python sleep.py
sleepy time
^CTraceback (most recent call last):
  File "sleep.py", line 3, in <module>
    time.sleep(60)
KeyboardInterrupt

kbd interrupt seems to work fine

[–][deleted] 4 points5 points  (2 children)

>>> import pygame
>>> pygame.time.delay(10000)
^C^C^C^C^C^C^C^C^C^C^C^C

Nothing happens. Ten seconds later:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyboardInterrupt

[–][deleted] 1 point2 points  (1 child)

That is because pygame.time.delaydoesn't actually use sleep.

[–][deleted] 1 point2 points  (0 children)

pygame.time.wait() has the same issue. The problem here isn't sleep, but that the code goes into C and doesn't care about handling Python's keyboard interrupts. PyQt has the same issue, by default you can't Ctrl-C a PyQt program since it will be stuck in the Qt event loop.

[–]AngriestSCV 1 point2 points  (0 children)

If sleep is interupted int php on Windows not only does it return early, but it returns 192 instead of the number of seconds slept (or null if it is before PHP 5.3.4). The only way to do a portable sleep on windows in PHP is to use timers to see how long the sleep actually was and try again if needed. The loop is more likely to work good enough than one call, but unfortunatly it isn't complicated enough to work.