可爱的 Python: 用 Python 生成器实现“轻便线程”
2007-03-29 12:04:49 来源:WEB开发网切换开销
在轻便线程之间切换开销很小,但还不是完全没有开销。为了测试这种情况,我构建了一个执行 某种工作(不过大约是您在线程中按道理可以完成的最少量)的示例。因为线程调度程序 真的等同于“执行 A,接着执行 B,然后执行 C,等等”的指令,所以要在主函数中创建一个完全并行的情况也不困难。
清单 3. overhead.py 示例脚本
from
__future__
import
generators
import
time
TIMES = 100000
def
stringops():
for
n
in
xrange(TIMES):
s =
"Mary had a little lamb"
s = s.upper()
s =
"Mary had a little lamb"
s = s.lower()
s =
"Mary had a little lamb"
s = s.replace('a','A')
def
scheduler():
for
n
in
xrange(TIMES):
for
thread
in
threads: thread.next()
def
upper():
while
1:
s =
"Mary had a little lamb"
s = s.upper()
yield
None
def
lower():
while
1:
s =
"Mary had a little lamb"
s = s.lower()
yield
None
def
replace():
while
1:
s =
"Mary had a little lamb"
s = s.replace(
'a'
,
'A'
)
yield
None
if
__name__==
'__main__':
start = time.clock()
stringops()
looptime = time.clock()-start
print
"LOOP TIME:"
, looptime
global
threads
threads.append(upper())
threads.append(lower())
threads.append(replace())
start = time.clock()
scheduler()
threadtime = time.clock()-start
print
"THREAD TIME:"
, threadtime
更多精彩
赞助商链接