# -*- coding: utf-8 -*- """Демо: perf_counter против time.time и process_time. Запуск из корня курса: python lab01_sequential/examples/01_perf_counter_demo.py Показывает: - почему time.time() для замеров плох (не монотонные часы); - как perf_counter и process_time диагностируют I/O-bound задачу. """ import os import sys import time sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) def demo_time_vs_perf(): print("--- time.time() против time.perf_counter() ---") t1 = time.time() p1 = time.perf_counter() time.sleep(0.05) t2 = time.time() p2 = time.perf_counter() print(f"time.time(): {(t2 - t1) * 1000:8.2f} мс (точность зависит от ОС)") print(f"time.perf_counter():{(p2 - p1) * 1000:8.2f} мс (монотонные, наносекундное разрешение)") def demo_cpu_vs_io(): print("\n--- CPU-bound против I/O-bound: perf_counter vs process_time ---") # CPU-bound: считаем t0 = time.perf_counter() c0 = time.process_time() s = 0.0 for i in range(3_000_000): s += i ** 0.5 cpu_wall = time.perf_counter() - t0 cpu_proc = time.process_time() - c0 # I/O-bound: ждём (имитация сетевых запросов) t0 = time.perf_counter() c0 = time.process_time() for _ in range(10): time.sleep(0.05) # «ожидание ответа сервера» io_wall = time.perf_counter() - t0 io_proc = time.process_time() - c0 print(f"{'':14}{'настенное, c':>14}{'процессорное, c':>18}{'доля сна':>10}") print(f"{'CPU-bound':14}{cpu_wall:>14.3f}{cpu_proc:>18.3f}" f"{100 * (1 - cpu_proc / cpu_wall):>9.0f}%") print(f"{'I/O-bound':14}{io_wall:>14.3f}{io_proc:>18.3f}" f"{100 * (1 - io_proc / io_wall):>9.0f}%") print("\nВывод: у I/O-задачи процессор почти всё время спит —") print("именно поэтому потоки/asyncio могут её ускорить (лабы 2 и 6).") if __name__ == "__main__": demo_time_vs_perf() demo_cpu_vs_io()