程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Mastering the Greenlet module of learning notes for Python introductory development

編輯:Python

The point of this section

master greenlet modular
The duration of this section needs to be controlled 5 Within minutes

One greenlet modular

If we have... In a single thread 20 A mission , To switch between multiple tasks , Use yield The generator is too cumbersome ( You need to get the generator initialized once first , Then call send... Very trouble ), While using greenlet Modules can do this very simply 20 Direct task switching

# install :pip3 install greenlet
from greenlet import greenlet
def eat(name):
print('%s eat 1' %name)
g2.switch('egon')
print('%s eat 2' %name)
g2.switch()
def play(name):
print('%s play 1' %name)
g1.switch()
print('%s play 2' %name)
g1=greenlet(eat)
g2=greenlet(play)

g1.switch(‘egon’)# For the first time switch The parameter is passed in , No need for
Simple switching ( In the absence of io In case of or without repeated operation of opening memory space ), On the contrary, it will reduce the execution speed of the program

# Sequential execution
import time
def f1():
res=1
for i in range(100000000):
res+=i
def f2():
res=1
for i in range(100000000):
res*=i
start=time.time()
f1()
f2()
stop=time.time()
print('run time is %s' %(stop-start)) #10.985628366470337
# Switch
from greenlet import greenlet
import time
def f1():
res=1
for i in range(100000000):
res+=i
g2.switch()
def f2():
res=1
for i in range(100000000):
res*=i
g1.switch()
start=time.time()
g1=greenlet(f1)
g2=greenlet(f2)
g1.switch()
stop=time.time()
print('run time is %s' %(stop-start)) # 52.763017892837524

greenlet It just provides a comparison generator More convenient switching mode , When cutting to a task execution, if io, Then block in place , It's still not solved IO The problem of automatic switching to improve efficiency .

This one in a single thread 20 The code of tasks usually has both calculation and blocking operations , We could be on a mission 1 When there's a jam , Just use the blocked time to perform the task 2.... such , To improve efficiency , And that's where it comes in Gevent modular .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved