💡 Problem Formulation: Chances are you’ve already figured out that you can get your Python program to sleep for one second using
time.sleep(1). But how do you sleep for less than a second, e.g., for half a second (0.5s), milliseconds, or even microseconds?
Method 1: Use time.sleep()
time.sleep(seconds) function halts the Python program for a specified amount of seconds. You can pass a floating point number for subsecond precision. For example,
time.sleep(0.5) sleeps for 0.5 seconds and
time.sleep(0.1) sleeps for 100 milliseconds.
import time print('hello...') time.sleep(0.5) print('... world')
The output is first:
… and then 0.5 seconds (500 milliseconds) later:
🅰️ Warning: Even though you can pass a fractional second such as 0.001 for one millisecond into the
time.sleep() function, the actual delay may be higher because your Python interpreter, operating system, and hardware don’t really provide this fine granularity.
The following may be an imperfect alternative, although it may run into the same problem. After that, in Method 3, I’ll give you another more precise alternative.
Method 2: Use Threading Timer
import threading and create a timer object
t using t =
threading.Timer(seconds, func). Then use
t.start() to execute
func() after 0.5 seconds. The
Timer() constructor also allows optional
kwargs arguments if you want to pass values into the function call.
from threading import Timer def world(): print("... world") t = Timer(0.5, world) print('hello...') t.start() # prints '... world' after 0.5 seconds
Like in the first method, the output first prints:
… and then 0.5 seconds (500 milliseconds) later:
Method 3: Asyncio Sleep
An easy way is to use
asyncio.sleep(0.001), for instance, to get your Python program to sleep for 1 millisecond. Import
asyncio, define an asynchronous function using
async def with the body statement
await asyncio.sleep(seconds), and run the asynchronous function using
asyncio.run() passing the function object.
Here’s a minimal example you can use as a template:
import asyncio async def main(): await asyncio.sleep(0.001) # sleep for approx 1 millisecond print('world') print('hello') asyncio.run(main())
The output is simply:
Except that the second
print() statement is only executed after a 1-millisecond sleep.
You can learn more on asynchronous functions in my blog post here:
💡 Recommended: Python Async Function
Also check out my best-selling programming textbook, it’s fun! 👇😊
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.