shivan
shivan

Reputation: 133

Which is more efficient? threading.Thread vs threading.Timer

This is more out of theoretical curiosity than an actual problem I am having.

Say you want to run some code at a regular interval, what are the pros and cons of using a Timer vs using a thread + time.sleep in terms of CPU consumption? The two below approaches do the same. I am aware that the Thread approach is not exactly one second interval, but rather adds a delay after each execution, which can matter if the task_function operation takes a long time. I am also aware that there are many other ways to solve this problem, but lets focus on the threading package.

Timer approach

def task_function():
   print(time.time())

def task():
   task_function()
   threading.Timer(1,task).start() 
task()

Thread approach

def task_function():
    while True:
        print(time.time())
        time.sleep(1)

threading.Thread(target=task_function).start()

I read somewhere that starting a thread is quite resource intensive. So I wonder that if you had some code you wanted to run every 0.1 seconds, would the Timer approach not be sub-optimal since a new thread has to be started so often?

Upvotes: 0

Views: 903

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155363

If the code must repeat on an interval, use the plain Thread (to be clear, Timer is just a thin wrapper around a Thread in the first place; it's implemented as a subclass). Spawning a new thread (via Timer) 10x a second is wasteful, and gains you nothing in any event.

You should make the worker thread a daemon thread though, unless you really want it to keep the process alive indefinitely.

Upvotes: 2

Related Questions