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命令行参数解析工具 docopt 安装和应用过程详解

什么是 docopt? 1、docopt 是一种 Python 编写的命令行执行脚本的交互语言。 它是一种语言! 它是一种语言! 它是一种语言! 2、使用这种语言可以在自己的脚本中,添...

python 中split 和 strip的实例详解

 python 中split 和 strip的实例详解 一直以来都分不清楚strip和split的功能,实际上strip是删除的意思;而split则是分割的意思。 python...

Python随机函数库random的使用方法详解

Python随机函数库random的使用方法详解

前言 众所周知,python拥有丰富的内置库,还支持众多的第三方库,被称为胶水语言,随机函数库random,就是python自带的标准库,他的用法极为广泛,除了生成比较简单的随机数外,还...

Python 实现数据库更新脚本的生成方法

我在工作的时候,在测试环境下使用的数据库跟生产环境的数据库不一致,当我们的测试环境下的数据库完成测试准备更新到生产环境上的数据库时候,需要准备更新脚本,真是一不小心没记下来就会忘了改了哪...

python决策树之C4.5算法详解

python决策树之C4.5算法详解

本文为大家分享了决策树之C4.5算法,供大家参考,具体内容如下 1. C4.5算法简介   C4.5算法是用于生成决策树的一种经典算法,是ID3算法的一种延伸...