# Timer 模块

这是一个同时支持标准 Python 和 MicroPython 的计时器模块，提供了精确的时间测量功能。

## 特性

- 支持标准 Python 和 MicroPython 环境
- 提供毫秒级精度的时间测量
- 支持多种使用方式：基本用法、上下文管理器和装饰器
- 自动检测运行环境并使用合适的时间函数

## 安装

直接将 `timer` 目录复制到你的项目中即可。

## 使用方法

### 1. 基本用法

```python
import timer

t = timer.Timer()
t.start()
# 你的代码
t.stop()
print(f"耗时: {t.elapsed_ms()}ms")
```

### 2. 上下文管理器

```python
with timer.Timer() as t:
    # 你的代码
print(f"耗时: {t.elapsed_ms()}ms")
```

### 3. 装饰器

```python
from timer import measure_time

@measure_time
def your_function():
    # 你的代码
    pass
```

### 4. 多次测量

```python
t = timer.Timer()

# 第一次测量
t.start()
# 代码1
t.stop()
print(f"第一次: {t.elapsed_ms()}ms")

t.reset()  # 重置计时器

# 第二次测量
t.start()
# 代码2
t.stop()
print(f"第二次: {t.elapsed_ms()}ms")
```

## API 参考

### Timer 类

#### 方法

- `start()`: 开始计时
- `stop()`: 停止计时
- `reset()`: 重置计时器
- `elapsed_ms()`: 返回经过的毫秒数
- `elapsed_seconds()`: 返回经过的秒数

### 辅助函数

- `measure_time`: 用于测量函数执行时间的装饰器
- `sleep_ms(ms)`: 休眠指定的毫秒数
- `MICROPYTHON`: 布尔值，指示是否在 MicroPython 环境中运行
- `IMPLEMENTATION`: 字符串，当前 Python 实现的名称

## 注意事项

1. 在 MicroPython 中使用时，确保使用 `import timer` 而不是 `from timer import Timer`
2. 时间测量的精度取决于运行环境：
   - 标准 Python 使用 `time.perf_counter()`
   - MicroPython 使用 `time.ticks_ms()`

## 示例

查看 `timer_example.py` 获取完整的使用示例。

## 兼容性

- 标准 Python 3.x
- MicroPython 1.x 及以上