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

相关文章

从零学python系列之教你如何根据图片生成字符画

从零学python系列之教你如何根据图片生成字符画

说下思路吧: 原图->灰度->根据像素亮度-映射到指定的字符序列中->输出。字符越多,字符变化稠密。效果会更好。如果根据灰度图的像素亮度范围制作字符画,效果会更好。如果...

python中seaborn包常用图形使用详解

python中seaborn包常用图形使用详解

seaborn包是对matplotlib的增强版,需要安装matplotlib后才能使用。 所有图形都用plt.show()来显示出来,也可以使用下面的创建画布 fig,ax=plt...

在pycharm上mongodb配置及可视化设置方法

在pycharm上mongodb配置及可视化设置方法

一、mongodb安装 在官网下载适应于自己平台的mongodb,在此安装环境为Windows7-64bit 下载完成后直接安装,连续点击next选项直到,此处注意!!!!! 切勿勾...

Python检测数据类型的方法总结

Python检测数据类型的方法总结

我们在用python进行程序开发的时候,很多时候我们需要检测一下当前的变量的数据类型。比如需要在使用字符串操作函数之前先检测一下当前变量是否是字符串。下面小编给大家分享一下在python...

Python3中的bytes和str类型详解

Python 3最重要的新特性之一是对字符串和二进制数据流做了明确的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的方式...