在Python中设置计时器可以通过以下几种方法:
1. 使用`time.time()`函数:
import time
time_start = time.time() 开始计时
要执行的代码
time_end = time.time() 结束计时
execution_time = time_end - time_start 计算执行时间
print(f"代码执行时间为:{execution_time}秒")
2. 使用`timeit`模块:
import timeit
code_to_test = """
这里放入需要计时的代码
"""
execution_time = timeit.timeit(code_to_test, number=1000) 执行1000次并计算平均时间
print(f"代码执行平均时间为:{execution_time}秒")
3. 自定义计时器类:
import time
class Timer:
def __init__(self):
self.prompt = "未开始计时..."
self.lasted = []
self.begin = 0
self.end = 0
def 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 threading
import time
cancel_tmr = False
def start_timer(func):
def wrapper():
nonlocal cancel_tmr
timer = threading.Timer(5, func) 设置5秒后执行
timer.start()
while not cancel_tmr:
time.sleep(0.1)
return wrapper
@start_timer
def my_function():
print("函数执行中...")
5. 使用`schedule`模块进行定时任务调度:
import schedule
import time
def job(text="I'm working"):
print(text)
schedule.every(1).minutes.do(job) 每分钟执行一次job函数
while True:
schedule.run_pending()
time.sleep(1)
以上是Python中设置计时器的几种方法。您可以根据需要选择合适的方法进行使用