1

I'm reading a tutorial about gevent, and it provids sample codes for a demonstrastion for synchronous and asynchronous cases:

import gevent
import random

def task(pid):
    """
    Some non-deterministic task
    """
    gevent.sleep(random.randint(0,2)*0.001)
    print('Task', pid, 'done')

def synchronous():
    for i in range(1,10):
        task(i)

def asynchronous():
    threads = [gevent.spawn(task, i) for i in xrange(1000)]
    gevent.joinall(threads)

This article explains that 'the order of execution in the async case is essentially random and that the total execution time in the async case is much less than the sync case'. So I used time module to test it:

print('Synchronous:')
start1 = time.clock()
synchronous()
end1 = time.clock()
print "%.2gs" % (end1-start1)

print('Asynchronous:')
start2 = time.clock()
asynchronous()
end2 = time.clock()
print "%.2gs" % (end2-start2)

However, the time run by 'asynchronous' is much longer than 'synchronous':

ubuntu@ip:/tmp$ python gevent_as.py
Synchronous:
0.32s
Asynchronous:
0.64s
ubuntu@ip:/tmp$ python gevent_as.py
Synchronous:
0.3s
Asynchronous:
0.61s

I want to know what's wronge with my test program? Thanks.

zfz
  • 1,597
  • 1
  • 22
  • 45

2 Answers2

1

It is the problem of time.clock(), that doesn't work properly under ubuntu. See the link for details: Python - time.clock() vs. time.time() - accuracy?

I changed the test program:

print('Synchronous:')
start1 = time.time()
synchronous()
end1 = time.time()
print "%.2gs" % (end1-start1)

print('Asynchronous:')
start2 = time.time()
asynchronous()
end2 = time.time()
print "%.2gs" % (end2-start2)

Then the test speed of 'asynchronous' is much faster than 'synchronous':

ubuntu@ip:/tmp$ python gevent_as.py
Synchronous:
1.1s
Asynchronous:
0.057s
Community
  • 1
  • 1
zfz
  • 1,597
  • 1
  • 22
  • 45
0

Probably the sleeps are very small and overhead matters. Try replacing 0.001 with 0.1.

Denis
  • 3,760
  • 25
  • 22