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

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Java及python正则表达式详解

Java及python正则表达式详解

正则表达式语法及常用元字符: 正则表达式有元字符及不同组合来构成,通过巧妙的构造正则表达式可以匹配任意字符串,并完成复杂的字符串处理任务。 常用的元字符有: 其中在使用反斜线时要注意:如...

Flask框架Flask-Login用法分析

本文实例讲述了Flask框架Flask-Login用法。分享给大家供大家参考,具体如下: Flask-Login插件中带了6种信号,可以基于其中的信号做一些额外工作,比如user_log...

Python使用pickle模块报错EOFError Ran out of input的解决方法

本文实例讲述了Python使用pickle模块报错EOFError Ran out of input的解决方法。分享给大家供大家参考,具体如下: 遇到了 EOFError:Ran out...

从运行效率与开发效率比较Python和C++

之前有人一直在说python怎么怎么好用,也有人说C++太难了,下面我做了一些笔记: 1、运行效率:C++ >> Python Python代码和C++最终都会变成CPU指令...

浅谈Python 列表字典赋值的陷阱

今天在用python刷leetcode 3Sum problem时,调入到了一个大坑中,检查半天并没有任何逻辑错误,但输出结果却总是不对,最终通过调试发现原来python中list和di...