Lua vs Python
By Michael Doornbos
- 2 minutes read - 358 words123
Introduction
Unscientific Benchmarks
Don’t get too twisted up about how scientific these are. I’m looking to do a rough comparison of some common tasks here.
I initially just did a simple addition.
Add all of the numbers from 1 to n.
Then I started to think about the fact that maybe the Lua startup time was a big factor in my numbers so I made it longer and configurable, with a way to keep track of a number of runs and give me a percentage difference.
time python run_sum_benchmark.py -n 50000000 -t 5
Yes, you can more easily sum natural numbers…
This formula comes from the mathematical definition of the sum of the first \(n\) natural numbers:
()\text{Sum} = 1 + 2 + 3 + \dots + n = \frac{n \cdot (n + 1)}{2}()
This formula is derived from the observation that pairing numbers from opposite ends of the series (e.g., \( 1 + n, 2 + (n-1), \dots \)) results in \(n/2\) pairs of equal sums, each being \( n+1 \). Multiplying the number of pairs (\( n/2 \)) by the value of each pair (\( n+1 \)) gives the total sum.
The // 2 in Python’s implementation ensures that the division is performed as integer division, avoiding fractional results that are irrelevant since the sum of natural numbers is always an integer.
In simpler terms:
- Multiplication first calculates \( n \cdot (n+1) \).
- Division by 2 adjusts for the pairing logic inherent in the formula.
For \( n = 500,000,000 \), this avoids iterating through all numbers individually, significantly speeding up the calculation.
Twelve
x times faster vs percent
When our benchmark says “Language A was \(p\%\) faster than Language B”, we can convert this to a multiplier:
\(%\) \text{Multiplier} = \frac{p + 100}{100} $ For example, with 417.4%: \( \text{Multiplier} = \frac{417.4 + 100}{100} = \frac{517.4}{100} = 5.174 \)%$
So you’re saying it’s 5.174 times faster…
Conversely, to get the percentage from a multiplier \(m\):
\(%\) p = (m - 1) \times 100 $ For example, with multiplier 5.174: \( p = (5.174 - 1) \times 100 = 4.174 \times 100 = 417.4\% \)%$