Python Performance Testing: Comparing Logical Operations, Built‑in Functions, and Class Implementations
This article examines Python execution speed by benchmarking simple arithmetic, logical checks, built‑in functions like max, and three class‑based point‑in‑rectangle implementations, revealing that straightforward if‑statements are often fastest while highlighting practical tips for writing performant Python code.
Many developers wonder why their code runs slowly; the author shares a personal anecdote about a high‑performance algorithm for crack‑stress analysis that runs in minutes on a laptop, contrasting it with slower student implementations.
The discussion then turns to performance versus development cost, especially in commercial fluid‑dynamics simulation software, and introduces the theme of the article: performance.
1. Guiding principle of "beautiful code" – functionality comes first, then performance, but performance can be an endless pursuit.
Performance is judged against typical user‑experience expectations (e.g., operations completing within 0.1 s).
2. Sacrificing performance for organizational freedom and talent flexibility – more tools for architects, lower skill requirements, and shorter development cycles.
Python Performance Tests
Test 1: Logical judgment vs. basic arithmetic
import time
def get_time():
return time.time()
a = 1
b = 2
t0 = get_time()
for i in range(100000):
if a + b:
pass
t1 = get_time()
for i in range(100000):
c = a > b
t2 = get_time()
for i in range(100000):
if a > b:
pass
t3 = get_time()
print("add time:", t1-t0)
print("> time:", t2-t1)
print("if time:", t3-t2)Results show that logical checks and basic arithmetic are on the same order (≈1e‑5 ms per loop), with assignment adding a few nanoseconds.
Test 2: Built‑in max vs. if‑statement vs. custom max1
import time
def get_time():
return time.time()
def max1(a,b):
if a > b:
return a
else:
return b
a = 1
b = 2
c = 0
t0 = get_time()
for i in range(100000):
if a > b:
c = a
else:
c = b
t1 = get_time()
for i in range(100000):
c = max(a, b)
t2 = get_time()
for i in range(100000):
c = max1(a,b)
t3 = get_time()
print("check time:", t1-t0, "rate:", "1")
print("max time:", t2-t1, "rate", (t2-t1)/(t1-t0))
print("max1 time:", t3-t2, "rate", (t3-t2)/(t1-t0))The direct if‑statement is fastest; the built‑in max is about twice as slow, and the custom max1 about 1.5× slower, illustrating that built‑ins may involve extra checks.
Test 3: Class implementations for point‑in‑rectangle checks
Three classes are compared:
Area1 – uses max and abs to compute a distance metric.
Area2 – replaces max with explicit if comparisons.
Area0 – performs only simple boundary checks with if statements.
class Area1(Rect):
def __init__(self, x, y, w, h):
super().__init__(x, y, w, h)
@property
def center(self):
return self.x + self.w/2, self.y + self.h/2
def norm(self, pos=None):
wph = self.w / self.h
if pos is not None:
norm0 = max(abs(pos[0] - self.center[0]), wph * abs(pos[1] - self.center[1]))
return norm0
else:
radius = max(abs(self.x - self.center[0]), wph * abs(self.y - self.center[1]))
return radius class Area2(Rect):
def __init__(self, x, y, w, h):
super().__init__(x, y, w, h)
@property
def center(self):
return self.x + self.w/2, self.y + self.h/2
def norm(self, pos):
if abs(pos[0] - self.center[0]) > self.wph * abs(pos[1] - self.center[1]):
return abs(pos[0] - self.center[0])
return self.wph * abs(pos[1] - self.center[1])
def __contains__(self, pos):
pos_norm = self.norm(pos)
if pos_norm > self.radius:
return False
else:
return True class Area0(Rect):
def __init__(self, x, y, w, h):
super().__init__(x, y, w, h)
@property
def center(self):
return self.x + self.w/2, self.y + self.h/2
def __contains__(self, pos):
if pos[0] < self.x:
return False
if pos[0] > self.x + self.w:
return False
if pos[1] < self.y:
return False
if pos[1] > self.y + self.h:
return False
return TrueBenchmarking these classes (100 000 iterations each) yields:
Area0: 0.0170 s rate: 1
Area1: 0.236 s rate: 13.89
Area2: 0.120 s rate: 7.06
check1: 0.222 s rate: 13.07Simple boundary checks (Area0) are dramatically faster; the distance‑based approaches incur significant overhead.
Conclusions and tips
Assignment, comparison, and basic arithmetic are all on the same nanosecond scale; use them freely.
Write functions that do exactly what is needed—no extra work.
Move any computation that does not depend on the loop outside the loop.
Encapsulating complex logic in functions does not necessarily hurt performance.
The article emphasizes that while elegant algorithms and architectures are valuable, they often trade off raw performance, and that understanding language‑level costs is essential, especially for compute‑intensive fields like AI.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
