Python – is time.sleep(n) cpu intensive? [duplicate]

No, it isn’t CPU intensive.

The documentation says:

Suspend execution for the given number of seconds.

Python can’t actually guarantee that in every possible implementation, this means the OS will never schedule your process during a sleep. But on each platform, Python tries to do something appropriate to block for the specified time without using any CPU. On some platforms, that may still mean a little bit of CPU, but it’s going to be as little as reasonably possible.

In particular, since you asked about linux, and presumably CPython:

On linux, and most other POSIX platforms, it will generally use select. See the 3.3 source.

The man page makes it pretty clear that select suspends until signal, timeout, or ready I/O (and in this case, there are no fds, so the latter is impossible).

You can read the kernel source for full details, but basically, unless there are any unexpected signals, you won’t be scheduled at all, except possibly a tiny amount of spinning at the very start of the select (as an optimization for the cases where select can return almost immediately).


In the middle of your summary, the question changes from “is sleep CPU-intensive” to “should I use sleep, or a cron job?”

Either way, you’re not burning any CPU while waiting around. There are some pros and cons, but most of them are trivial. From (roughly, and subjectively) most important to least, a cron job:

  • allows configuration—e.g., changing the schedule—without editing source code.
  • requires configuration to work.
  • means less code—meaning fewer bugs, and less for any future readers to understand.
  • will persist across system shutdown.
  • will fire again even if your script exits with an exception or a signal.
  • may fire either 0, 1 or N times if its scheduled interval is missed N times (this isn’t specified, and different cron implementations do different things), instead of guaranteed 0.
  • has a better chance of handling system clock changes.
  • has to pay for process launch, interpreter startup, etc. each time it fires.
  • doesn’t waste page table and process table space, because there is no process running and no memory mapped.

Leave a Comment