python-单线程和多线程对比

import time
import threading
from MyThread import MyThread

def fib(x):
    time.sleep(0.0005)
    if x<2:
        return 1
    return (fib(x-2)+fib(x-1))

def fac(x):
    time.sleep(0.1)
    if x<2:
        return 1
    return(x*fac(x-1))

def sum(x):
    time.sleep(0.1)
    if x<2:
        return 1
    return (x+sum(x-1))

funcs = [fib,fac,sum]

n = 12

def main():
    nfuncs = range(len(funcs))

    print('***SINGLE THREAD')
    for i in nfuncs:
        print('starting',funcs[i].__name__,'at:',time.ctime())
        print(funcs[i](n))
        print(funcs[i].__name__,'finished at:', time.ctime())

    print('\n*** MULTIPLE THREAD')
    threads = []
    for i in nfuncs:
        t = MyThread(funcs[i],(n,),funcs[i].__name__)     #此处使用了子类调用线程的方法,需要注意,线程的变量需要是元组形式,因此此处需要使用(n,)
        threads.append(t)   #use list's method append, adding an element in list 'threads'

    for i in nfuncs:
        threads[i].start()

    for i in nfuncs:
        threads[i].join()
        print(threads[i].getResult())     #MyThread中已经重新定义了run()方法,可以计算res,通过getResult返回res结果

    print('all DONE')

你可能感兴趣的:(python)