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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

python 设置文件编码格式的实现方法

如果要在python2的py文件里面写中文,则必须要添加一行声明文件编码的注释,否则python2会默认使用ASCII编码。(python3已经没有这个问题了,python3默认的文件编...

Python Django框架防御CSRF攻击的方法分析

本文实例讲述了Python Django框架防御CSRF攻击的方法。分享给大家供大家参考,具体如下: 项目名/settings.py(项目配置,csrf中间件配置): MIDDLEW...

python通过openpyxl生成Excel文件的方法

本文实例讲述了python通过openpyxl生成Excel文件的方法。分享给大家供大家参考。具体如下: 使用前请先安装openpyxl: easy_install openpyxl...

Python中的单继承与多继承实例分析

本文实例讲述了Python中的单继承与多继承。分享给大家供大家参考,具体如下: 单继承 一、介绍 Python 同样支持类的继承,如果一种语言不支持继承,类就没有什么意义。派生类的定义如...

windows下python 3.6.4安装配置图文教程

windows下python 3.6.4安装配置图文教程

windows下python的安装教程,供大家参考,具体内容如下 —–因为我是个真小白,网上的大多入门教程并不适合我这种超级超级小白,有时候还会遇到各种各样的问题,因此记录一下我的安装过...