python定时执行指定函数的方法

(编辑:jimmy 日期: 2024/10/3 浏览:2)

本文实例讲述了python定时执行指定函数的方法。分享给大家供大家参考。具体实现方法如下:

# time a function using time.time() and the a @ function decorator
# tested with Python24  vegaseat  21aug2005
import time
def print_timing(func):
  def wrapper(*arg):
    t1 = time.time()
    res = func(*arg)
    t2 = time.time()
    print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0)
    return res
  return wrapper
# declare the @ decorator just before the function, invokes print_timing()
@print_timing
def getPrimeList(n):
  """ returns a list of prime numbers from 2 to < n using a sieve algorithm"""
  if n < 2: return []
  if n == 2: return [2]
  # do only odd numbers starting at 3
  s = range(3, n+1, 2)
  # n**0.5 may be slightly faster than math.sqrt(n)
  mroot = n ** 0.5
  half = len(s)
  i = 0
  m = 3
  while m <= mroot:
    if s[i]:
      j = (m*m-3)//2
      s[j] = 0
      while j < half:
        s[j] = 0
        j += m
    i = i+1
    m = 2*i+3
  return [2]+[x for x in s if x]
if __name__ == "__main__":
  print "prime numbers from 2 to <10,000,000 using a sieve algorithm"
  primeList = getPrimeList(10000000)
  time.sleep(2.5)
"""
my output -->
prime numbers from 2 to <10,000,000 using a sieve algorithm
getPrimeList took 4750.000 ms
"""

希望本文所述对大家的Python程序设计有所帮助。

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。