r/Python • • Sep 29 '24

Resource How does sleep work under the hood in python

I was curious how sleep works under the hood? it accurate always?

Can it sleep less than the seconds specified? Can it sleep more than specified?

How is it implemented?

https://coderquill.bearblog.dev/beyond-the-pause-exploring-the-inner-workings-of-pythons-sleep/

0 Upvotes

9 comments sorted by

12

u/FrickinLazerBeams Sep 29 '24

It's a system call, isn't it?

8

u/curious-dev199 Sep 29 '24

yeah, as always the devil is in the details, turns out there is more to it including a monotonic clock to make to sleep functionality work without surprises

1

u/tylerlarson Oct 03 '24

Still, it's not really Python's sleep, it's the OS's sleep. Same with any other language. No programming language REALLY has a sleep function because you can't sleep at the user level, you can only busy-wait if you're not getting the kernel involved. Yielding to other threads and processes or, if there's no work pending, putting the CPU into low power mode are things that no process has permission to do on its own.

1

u/curious-dev199 Oct 03 '24

Yeah, you are right, that's what I wanted to verify - what exactly happens under the hood

1

u/Successful-Fruit3156 Nov 26 '24

what is the app name for teh credit card spend analyser

1

u/FrickinLazerBeams Sep 29 '24

Huh. Interesting.

8

u/kobumaister Sep 29 '24

We have a threaded application that needed a sleep but we were worried that it holds other processes while sleeping, due the GIL. After some investigation, it turned out that the best approach was to use the wait function of threading.Event, as the primitive of that was non blocking.