如何在Python中处理更复杂的计时需求,比如分段计时?
时间: 2025-01-01 18:36:13 浏览: 3
在Python中处理复杂的计时需求,比如分段计时,你可以使用类和函数来构建一个更健壮的计时器系统。例如,可以设计一个`SegmentedTimer`类,它包含开始、停止、暂停和继续等方法。下面是一个简单的示例:
```python
import time
from collections import defaultdict
class SegmentedTimer:
def __init__(self):
self.segments = defaultdict(lambda: {"start": None, "end": None})
def start_segment(self, label=None):
if label:
self.segments[label] = {"start": time.time()}
else:
label = "unnamed_segment"
self.segments[label]["start"] = time.time()
def stop_segment(self, label=None):
if label and label in self.segments:
self.segments[label]["end"] = time.time()
elif "unnamed_segment" in self.segments:
self.segments["unnamed_segment"]["end"] = time.time()
else:
print("No active segment to stop.")
def pause_segment(self, label):
if label in self.segments:
self.segments[label]["paused"] = time.time()
def resume_segment(self, label):
if label in self.segments and "paused" in self.segments[label]:
self.segments[label]["end"] = time.time()
del self.segments[label]["paused"]
def get_elapsed_time(self, label):
if label in self.segments:
return self.segments[label]["end"] - self.segments[label]["start"]
else:
return None
# 使用示例
timer = SegmentedTimer()
timer.start_segment('segment1') # 开始计时
time.sleep(2) # 模拟活动
timer.pause_segment('segment1')
time.sleep(1)
timer.resume_segment('segment1')
timer.stop_segment('segment1') # 停止并获取时间
阅读全文