在Python中设置计时器可以通过以下几种方法:
1. 使用`time.time()`函数:
import timetime_start = time.time() 开始计时要执行的代码time_end = time.time() 结束计时execution_time = time_end - time_start 计算执行时间print(f"代码执行时间为:{execution_time}秒")
2. 使用`timeit`模块:
import timeitcode_to_test = """这里放入需要计时的代码"""execution_time = timeit.timeit(code_to_test, number=1000) 执行1000次并计算平均时间print(f"代码执行平均时间为:{execution_time}秒")
3. 自定义计时器类:
import timeclass Timer:def __init__(self):self.prompt = "未开始计时..."self.lasted = []self.begin = 0self.end = 0def start(self):self.begin = time.localtime()print("计时开始....")def stop(self):self.end = time.localtime()self.calc()print("计时结束...")def calc(self):self.lasted = []self.prompt = "总共运行了 "for i in range(6):self.lasted.append(self.end[i] - self.begin[i])self.prompt += str(self.lasted[i]) + "秒 "
4. 使用`threading`模块创建计时器:
import threadingimport timecancel_tmr = Falsedef start_timer(func):def wrapper():nonlocal cancel_tmrtimer = threading.Timer(5, func) 设置5秒后执行timer.start()while not cancel_tmr:time.sleep(0.1)return wrapper@start_timerdef my_function():print("函数执行中...")
5. 使用`schedule`模块进行定时任务调度:
import scheduleimport timedef job(text="I'm working"):print(text)schedule.every(1).minutes.do(job) 每分钟执行一次job函数while True:schedule.run_pending()time.sleep(1)
以上是Python中设置计时器的几种方法。您可以根据需要选择合适的方法进行使用

