1+ import statistics
2+ import time
3+
4+ from books import Book , BookCollection
5+
6+
7+ def run_benchmark (iterations : int = 10000 , book_count : int = 1000 ) -> dict [str , float ]:
8+ collection = BookCollection ()
9+ collection .books = [
10+ Book (title = f"Book { index } " , author = "Benchmark Author" , year = 2000 + (index % 20 ))
11+ for index in range (book_count )
12+ ]
13+
14+ samples = []
15+ for _ in range (iterations ):
16+ start = time .perf_counter ()
17+ collection .list_books ()
18+ samples .append ((time .perf_counter () - start ) * 1_000_000 )
19+
20+ return {
21+ "iterations" : iterations ,
22+ "book_count" : book_count ,
23+ "mean_us" : statistics .mean (samples ),
24+ "median_us" : statistics .median (samples ),
25+ "min_us" : min (samples ),
26+ "max_us" : max (samples ),
27+ }
28+
29+
30+ if __name__ == "__main__" :
31+ results = run_benchmark ()
32+ print ("Benchmark: list_books" )
33+ print (f"Iterations: { results ['iterations' ]} " )
34+ print (f"Book count: { results ['book_count' ]} " )
35+ print (f"Mean: { results ['mean_us' ]:.3f} us" )
36+ print (f"Median: { results ['median_us' ]:.3f} us" )
37+ print (f"Min: { results ['min_us' ]:.3f} us" )
38+ print (f"Max: { results ['max_us' ]:.3f} us" )
0 commit comments