在Python中设置程序的执行时间可以通过多种方式实现,以下是几种常见的方法:
1. 使用`time`模块:
import time
start_time = time.time() 记录程序开始时间
执行程序代码
...
end_time = time.time() 记录程序结束时间
计算执行时间
execution_time = end_time - start_time
print(f"执行时间:{execution_time}秒")
2. 使用`timeit`模块:
import timeit
计算代码块的执行时间
execution_time = timeit.timeit('your_code_here', globals=globals(), number=1)
print(f"执行时间:{execution_time}秒")
3. 使用`schedule`库:
import schedule
import time
def job():
print("I'm running at 5:00am every day.")
设定定时任务
schedule.every().day.at("05:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)
4. 使用Windows任务计划程序:
打开任务计划程序。
创建基本任务。
设置任务开始时间和间隔。
选择“启动程序”,填写Python解释器的绝对路径和要执行的Python程序路径。
完成任务创建。
5. 使用`subprocess`模块和`threading.Timer`:
import subprocess
from threading import Timer
def call(args, timeout):
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
timer = Timer(timeout, lambda process: process.kill(), [p])
try:
timer.start()
stdout, stderr = p.communicate()
return_code = p.returncode
return (stdout, stderr, return_code)
finally:
timer.cancel()
测试
print(call(['hostname'], 2))
print(call(['ping', 'www.baidu.com'], 2))
以上方法可以帮助你设置Python程序的执行时间。请根据你的具体需求选择合适的方法