We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent b103eae commit bdb66deCopy full SHA for bdb66de
2 files changed
code/ch05-perf/specialize_final.py
@@ -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
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
@@ -22,6 +22,13 @@ def test_conversions() -> None:
assert_round_trip(t)
def round_trip(t: float) -> float:
return f_to_c(c_to_f(t))
@@ -40,7 +47,8 @@ def assert_round_trip(t: float) -> None:
if __name__ == "__main__":
t0 = datetime.datetime.now()
- test_conversions()
t1 = datetime.datetime.now()
dt = t1 - t0
0 commit comments