在Python中设置程序的执行时间可以通过多种方式实现,以下是几种常见的方法:
1. 使用`time`模块:
import timestart_time = time.time() 记录程序开始时间执行程序代码...end_time = time.time() 记录程序结束时间计算执行时间execution_time = end_time - start_timeprint(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 scheduleimport timedef 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 subprocessfrom threading import Timerdef 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.returncodereturn (stdout, stderr, return_code)finally:timer.cancel()测试print(call(['hostname'], 2))print(call(['ping', 'www.baidu.com'], 2))
以上方法可以帮助你设置Python程序的执行时间。请根据你的具体需求选择合适的方法

