同样在函数中连接pgsql,然后执行500次查询,
测试gevent模式、串行查询、多线程查询
数据如下:
multithread_test cost time: 2.45199990273
normal_test cost time: 4.04299998283
gevent_test cost time: 2.12800002098
结果 串行最慢4.4s, 多线程 2.45s ,gevent最快2.12 ,yes!
测试代码:
1 import gevent
2 import gevent.queue
3
4 import psycopg2
5 import psycopg2.extensions
6
7 import psycogreen.gevent
8
9 psycogreen.gevent.patch_psycopg()
10
11 sys.path.insert(0,'../')
12
13 import easymq
14
15 '''
16 在同一线程中,同一个连接conn上两次创建的cur将会是一样滴,因为是异步wait_read()缘故
17 所以要么每次创建数据库连接,要么使用dbpool
18 '''
19
20
21 def readThread():
22 conn = psycopg2.connect(database='postgres',user='postgres',password='111111')
23
24 # cur = conn.cursor(cursor_factory=psycopg2.extensions.DictCursor)
25 cur = conn.cursor(cursor_factory=psycopg2.extensions.cursor)
26
27 # cur.execute("select pg_sleep(%s)", (2,))
28 for n in range(10):
29 cur.execute("select CURRENT_DATE")
30 # print cur.fetchone()
31 # print 'read end..'
32 conn = None
33
34
35 def gevent_test():
36 jobs=[]
37 for n in range(100):
38 jobs.append(gevent.spawn(readThread))
39 gevent.joinall(jobs)
40
41 def normal_test():
42 for n in range(100):
43 readThread()
44
45 def multithread_test():
46 threads=[]
47 for n in range(100):
48 thread = threading.Thread(target=readThread)
49 threads.append(thread)
50 thread.start()
51 for thread in threads:
52 thread.join()
53
54 start = time.time()
55 normal_test()
56 end = time.time()
57 print 'normal_test cost time:',end-start
58
59 start = time.time()
60 gevent_test()
61 end = time.time()
62 print 'gevent_test cost time:',end-start
63
64 # start = time.time()
65 # multithread_test()
66 # end = time.time()
67 # print 'multithread_test cost time:',end-start
68