Reputation: 4469
i write a test case to compare thread and gevent's performance,
using multithread to do a task like:
import time
import threading
def sync_task():
#do something
time.sleep(1)
def multi_thread_run():
start = time.time()
for i in range(10):
t = threading.Thread(target=sync_task)
t.start()
end = time.time()
print("multi thread task executed in %f second"%(end-start))
print:
multi thread task executed in 0.002425 second
however, using gevent replace thread do same task:
import gevent
def async_task():
#do something
gevent.sleep(1)
def async_run():
start = time.time()
coroutins = []
for i in range(10):
coroutins.append(gevent.spawn(async_task))
gevent.joinall(coroutins)
end = time.time()
print("async task executed in %f second"%(end-start))
print:
async task executed in 1.002012 second
in many blog post I see coroutine is more effective than mutilthread, in this case, how to explain it?
Upvotes: 0
Views: 234
Reputation: 3951
That's because you didn't join
your Thread
- it means that program doesn't wait for thread to finish executing, and instead ends almost immediatelly.
Upvotes: 1