python定时执行指定函数的方法
本文实例讲述了python定时执行指定函数的方法。分享给大家供大家参考。具体实现方法如下:
#timeafunctionusingtime.time()andthea@functiondecorator #testedwithPython24vegaseat21aug2005 importtime defprint_timing(func): defwrapper(*arg): t1=time.time() res=func(*arg) t2=time.time() print'%stook%0.3fms'%(func.func_name,(t2-t1)*1000.0) returnres returnwrapper #declarethe@decoratorjustbeforethefunction,invokesprint_timing() @print_timing defgetPrimeList(n): """returnsalistofprimenumbersfrom2to<nusingasievealgorithm""" ifn<2:return[] ifn==2:return[2] #doonlyoddnumbersstartingat3 s=range(3,n+1,2) #n**0.5maybeslightlyfasterthanmath.sqrt(n) mroot=n**0.5 half=len(s) i=0 m=3 whilem<=mroot: ifs[i]: j=(m*m-3)//2 s[j]=0 whilej<half: s[j]=0 j+=m i=i+1 m=2*i+3 return[2]+[xforxinsifx] if__name__=="__main__": print"primenumbersfrom2to<10,000,000usingasievealgorithm" primeList=getPrimeList(10000000) time.sleep(2.5) """ myoutput--> primenumbersfrom2to<10,000,000usingasievealgorithm getPrimeListtook4750.000ms """
希望本文所述对大家的Python程序设计有所帮助。