对话实录
小白:(崩溃)我优化了半天代码,怎么知道到底有没有变快?
专家:(递上秒表)用时间测量工具!数据不会说谎!
时间测量四件套
1. 基础秒表:time.time ()
import time
start = time.time()
sum(range(1000000)) # 被测代码
end = time.time()
print(f"耗时:{end - start:.4f}秒") # -> 耗时:0.0414秒
专家提醒:适合粗略计时,精度约 1 毫秒!
2. 高精时钟:time.perf_counter ()
start = time.perf_counter()
sorted([3,1,4,1,5,9,2,6,5,3,5]) # 排序算法
end = time.perf_counter()
print(f"高精度耗时:{end - start:.6f}秒") #-> 高精度耗时:0.000006秒
3. time.process_time()
import time
start = time.process_time()
# 模拟一些计算密集型任务
result = 1
for i in range(1, 10000):
result *= i
end = time.process_time()
print(f"CPU时间:{end - start:.6f}秒") #->CPU时间:0.031250秒
专家解读:此方法主要测量进程使用 CPU 的时间,能更精准反映代码计算量对时间的消耗,不受系统其他活动干扰,适用于评估纯计算任务性能。
4. timeit.timeit()
import timeit
def test_function():
return sum([i**2 for i in range(1000)])
total_time = timeit.timeit(test_function, number = 1000)
print(f"1000次运行总耗时:{total_time:.6f}秒") #->1000次运行总耗时:0.106927秒
特别说明:timeit.timeit 函数方便在不同环境中准确测试代码性能。
实战案例
案例 1:比较算法性能
def test_sort(func):
start = time.perf_counter()
func([3,1,4,1,5,9,2,6,5,3,5]*1000)
return time.perf_counter() - start
print(f"冒泡排序耗时:{test_sort(sorted)}秒")
案例 2:网络请求计时
import requests
start = time.perf_counter()
response = requests.get("https://www.baidu.com")
print(f"请求耗时:{time.perf_counter() - start:.2f}秒")
print(f"状态码:{response.status_code}")
案例 3:上下文管理器方式计时
class Timer:
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, *args):
self.duration = time.perf_counter() - self.start
print(f"耗时:{self.duration:.3f}秒")
with Timer():
sum([i**2 for i in range(1000000)])
案例 4:文件读写性能测试
import time
def read_file():
with open('large_file.txt', 'r') as f:
data = f.read()
return data
start = time.perf_counter()
read_file()
print(f"读取文件耗时:{time.perf_counter() - start:.4f}秒")
def write_file():
with open('new_file.txt', 'w') as f:
for i in range(100000):
f.write(str(i) + '\n')
start = time.perf_counter()
write_file()
print(f"写入文件耗时:{time.perf_counter() - start:.4f}秒")
案例5: 装饰器自动计时
def timer(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__}耗时:{time.perf_counter() - start:.4f}秒")
return result
return wrapper
@timer
def heavy_calculation():
return sum(i**2 for i in range(10**6))
heavy_calculation()
案例 6: cProfile 模块进行性能分析
import cProfile
def complex_function():
result = 0
for i in range(1000000):
result += i * i
return result
cProfile.run('complex_function()')
cProfile 模块能生成详细的函数调用统计信息,包括每个函数被调用的次数、执行时间以及在函数内部调用其他函数的时间分布等。通过分析这些信息,开发者可以快速定位代码中的性能瓶颈,有针对性地进行优化。例如,在上述代码中,cProfile 的输出能直观展示complex_function函数内部的时间消耗情况,帮助开发者判断是否需要优化循环逻辑或采用更高效的数据结构。
案例 6: line_profiler 逐行分析
首先需要安装line_profiler库,使用pip install line_profiler命令进行安装。安装完成后,以下是使用示例:
from line_profiler import LineProfiler
def calculate_sum():
total = 0
for i in range(1000000):
total += i
return total
lp = LineProfiler()
lp.add_function(calculate_sum)
lp.run('calculate_sum()')
lp.print_stats()
line_profiler可以逐行分析函数的执行时间,精确到每一行代码的耗时情况。
小白:(献上膝盖)原来计时有这么多学问!
专家:(扶起小白)记住:优化前先测量,盲目优化是万恶之源!