Skip to content

Commit bdb66de

Browse files
committed
Specializing interpreter for python perf demo code.
1 parent b103eae commit bdb66de

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed

code/ch05-perf/specialize_final.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import datetime
2+
import math
3+
4+
5+
def f_to_c(f: float) -> float:
6+
"""Convert Fahrenheit to Celsius."""
7+
x = f - 32.0
8+
return x * (5 / 9)
9+
10+
11+
def c_to_f(c: float) -> float:
12+
"""Convert Celsius to Fahrenheit."""
13+
x = c * (9 / 5)
14+
return x + 32.0
15+
16+
17+
TEST_VALUES = [-459.67, -273.15, 0.0, 32.0, 42.0, 273.15, 100.0, 212.0, 373.15]
18+
19+
20+
def test_conversions() -> None:
21+
for t in TEST_VALUES:
22+
assert_round_trip(t)
23+
24+
25+
def test_speed():
26+
count = int(1_000_000 / len(TEST_VALUES))
27+
for _ in range(0, count):
28+
for t in TEST_VALUES:
29+
round_trip(t)
30+
31+
32+
def round_trip(t: float) -> float:
33+
return f_to_c(c_to_f(t))
34+
35+
36+
def assert_round_trip(t: float) -> None:
37+
# Round-trip Fahrenheit through Celsius:
38+
assert math.isclose(t, f_to_c(c_to_f(t))), f"{t} F -> C -> F failed!"
39+
print(f'{t:,.1f} F -> {f_to_c(t):,.1f} C')
40+
# Round-trip Celsius through Fahrenheit:
41+
assert math.isclose(t, c_to_f(f_to_c(t))), f"{t} C -> F -> C failed!"
42+
t2 = f_to_c(t)
43+
print(f'{t2:,.1f} C -> {c_to_f(t2):,.1f} F')
44+
print()
45+
46+
47+
if __name__ == "__main__":
48+
t0 = datetime.datetime.now()
49+
50+
# test_conversions()
51+
test_speed()
52+
53+
t1 = datetime.datetime.now()
54+
dt = t1 - t0
55+
print(f'Done in {dt.total_seconds() * 1000:.2f} ms')

code/ch05-perf/specialize_start.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,13 @@ def test_conversions() -> None:
2222
assert_round_trip(t)
2323

2424

25+
def test_speed():
26+
count = int(1_000_000 / len(TEST_VALUES))
27+
for _ in range(0, count):
28+
for t in TEST_VALUES:
29+
round_trip(t)
30+
31+
2532
def round_trip(t: float) -> float:
2633
return f_to_c(c_to_f(t))
2734

@@ -40,7 +47,8 @@ def assert_round_trip(t: float) -> None:
4047
if __name__ == "__main__":
4148
t0 = datetime.datetime.now()
4249

43-
test_conversions()
50+
# test_conversions()
51+
test_speed()
4452

4553
t1 = datetime.datetime.now()
4654
dt = t1 - t0

0 commit comments

Comments
 (0)