single-threaded and multithreaded execution comparison
In this chapter, we use recursion to calculate the Fibonacci, factorial, and additive functions to compare single-threaded and multi-threading.
Fibonacci, factorial and summation (mtfacfib.py):
?
1 ImportThreading2 fromTimeImportSleep, CTime3 ?4 classMyThread (Threading. Thread):5 def __init__(Self, func, args, name="'):6Threading. Thread.__init__(self)7Self.name =name8Self.func =func9Self.args =argsTen ? One defGetResult (self): A returnSelf.res - ? - defRun (self): the Print('Starting%s at:%s'%(Self.name, CTime ())) -Self.res = Self.func (*Self.args) - Print('%s finished at:%s'%(Self.name, CTime ())) - ? + ? - deffib (x): +Sleep (0.005) A ifX < 2: at return1 - return(FIB (x-2) + fib (x-1)) - ? - defFAC (x): -Sleep (0.1) - ifX < 2: in return1 - return(x * FAC (x-1)) to ? + defsum (x): -Sleep (0.1) the ifX < 2: * return1 $ return(x + sum (x-1))Panax Notoginseng ? -Funcs =[FIB, FAC, sum] then = 12 + ? A defMain (): theNfuncs =Range (len (funcs)) + ? - Print('* * Single THREAD') $ forIinchNfuncs: $ Print('Starting%s at:%s'% (Funcs[i].__name__, CTime ())) - Print(Funcs[i] (n)) - Print('%s finished at:%s'% (Funcs[i].__name__, CTime ())) the ? - Print('\n*** multiple THREADS')WuyiThreads = [] the forIinchNfuncs: -t = MyThread (Funcs[i], (n,), Funcs[i].__name__) Wu threads.append (t) - ? About forIinchNfuncs: $ Threads[i].start () - ? - forIinchNfuncs: - Threads[i].join () A Print(Threads[i].getresult ()) + ? the Print(' All done') - ? $ if __name__=='__main__': theMain ()
The output is:
1E:\project\test_temporary>python mtfacfib.py2***Single THREAD3Starting fib At:fri Jul 27 08:53:18 201842335Fib finished At:fri Jul 27 08:53:20 20186Starting FAC At:fri Jul 27 08:53:20 201874790016008FAC finished At:fri Jul 27 08:53:22 20189Starting sum At:fri Jul 27 08:53:22 2018Ten78 OneSum finished At:fri Jul 27 08:53:23 2018 A ? -***multiple THREADS -Starting fib At:fri Jul 27 08:53:23 2018 theStarting FAC At:fri Jul 27 08:53:23 2018 -Starting sum At:fri Jul 27 08:53:23 2018 -FAC finished At:fri Jul 27 08:53:24 2018 -Sum finished At:fri Jul 27 08:53:24 2018 +Fib finished At:fri Jul 27 08:53:25 2018 -233 +479001600 A78 atAll done
In a single-threaded run, simply call each function in turn, and display the corresponding result immediately after the function execution ends;
When running in multithreaded mode, the results are not displayed immediately, but when the thread ends, the GetResult () method is called to finally display the return value of each function.
Single-threaded and multithreaded execution contrast-python multithreaded programming