Cute Python: Implement "lightweight thread" with a Python generator:
Http://www-900.ibm.com/developerWorks/cn/linux/sdk/python/charm-25/index.shtml
The above mentioned: The result indicates that the version of the light thread runs twice in the time of the direct cycle, it is equivalent to the machine that is mentioned above, the lightweight thread is not running 3 seconds, and the direct cycle has run more than 6 seconds. Obviously, if each work unit is equivalent to twice the single string method call twice, ten times or more, then the proportion of thread overhead spending is correspondingly smaller.
From __future__ import generatorsimport timetimes = 100000
Def stringops (): for n in xrange (time): 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') defchuler (): for n in xrange (THREAD IN Threads: thread.next () def Upper (): while1: s = "Mary Had a Little Lamb" s = S.upper () yield Nonedef Lower (): While1: s = "Mary Had a little lamb" s = s.Lower () yield nonedef replace (): while1: s = "Mary Had a little lamb "s = s.replace ('a', 'a') yield noneif __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
However, my test results are just the opposite, and the light consumption is 0.6M, and the circulation has been used in 0.4m. Increase the Times parameters more obvious. The test confirmed my suspicion, it is estimated that the author or the translator is wrong.