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 实现上传图片并预览的3种方法(推荐)

python 实现上传图片并预览的3种方法(推荐)

在常见的用户注册页面,需要用户在本地选择一张图片作为头像,并同时预览。 常见的思路有两种:一是将图片上传至服务器的临时文件夹中,并返回该图片的url,然后渲染在html页面;另一种思路是...

Python查询阿里巴巴关键字排名的方法

本文实例讲述了Python查询阿里巴巴关键字排名的方法。分享给大家供大家参考。具体如下: 这里使用python库urllib及pyquery基本东西的应用,实现阿里巴巴关键词排名的查询,...

django的model操作汇整详解

django的model操作汇整详解

单表操作 增加数据 auther_obj = {"auther_name":"崔皓然","auther_age":1} models.auther.objects.create(...

Python使用正则实现计算字符串算式

在Python里面其实有一种特别方便实用的直接计算字符串算式的方法 那就是eval() s = '1+2*(6/2-9+3*(3*9-9))' print(eval(s)) #97....

浅谈python多进程共享变量Value的使用tips

浅谈python多进程共享变量Value的使用tips

前言: 在使用tornado的多进程时,需要多个进程共享一个状态变量,于是考虑使用multiprocessing.Value(对于该变量的具体细节请查阅相关资料)。在根据网上资料使用Va...