- This topic is empty.
-
AuthorPosts
-
March 21, 2026 at 6:24 am #6257
πΉ Introduction
When analyzing how fast a function runs, you may see code like this:
import time
L_N = [1]
for i in range(7):
L_N.append(L_N[-1] * 10)for N in L_N:
t = time.perf_counter()
km = convert_to_km(N)
dt = time.perf_counter() – t
print(f”convert_to_km({N}) took {dt} seconds ({1/dt}/sec)”)This code is used to measure performance of a function for different input sizes.
πΉ Context: What is happening here?
- Creating input sizes
L_N = [1]
for i in range(7):
L_N.append(L_N[-1] * 10)π This generates:
[1, 10, 100, 1000, …]
β Each input is 10Γ larger than the previous
- Looping through inputs
for N in L_N:
π We test the function with different sizes
- Measuring time
t = time.perf_counter()
km = convert_to_km(N)
dt = time.perf_counter() – tπ Steps:
- Start timer β “t”
- Run function β “convert_to_km(N)”
- Compute time taken β “dt”
πΉ The Key Line (Focus)
print(f”convert_to_km({N}) took {dt} seconds ({1/dt}/sec)”)
πΉ Step-by-Step Breakdown
β 1. “f”…”” β f-string
π Allows inserting values using “{}”
β 2. “convert_to_km({N})”
- “”convert_to_km(“” β text
- “{N}” β actual value
π Example:
convert_to_km(100)
β This is just display text, NOT a function call
β 3. “took {dt} seconds”
- “{dt}” = execution time
π Example:
took 0.002 seconds
β 4. “({1/dt}/sec)”
π This calculates speed
- “1/dt” = number of operations per second
Example:
dt = 0.002
1 / dt = 500π Output:
(500/sec)
πΉ Final Output Example
If:
N = 100
dt = 0.002π Output:
convert_to_km(100) took 0.002 seconds (500/sec)
πΉ Important Concept
π This line does NOT execute the function
The function is already executed here:
km = convert_to_km(N)
π The print line only reports results
πΉ Why This is Useful
This pattern helps you:
- Compare performance across inputs
- Understand scaling (time complexity)
- See both:
- β± Time taken (“dt”)
- β‘ Speed (“1/dt”)
πΉ Mental Model
π βFor input size N:
- how long did it take?
- how fast is it?β
πΉ One-Line Summary
π This print line converts raw timing into a human-readable performance report
πΉ Bonus Insight
- Small “dt” β faster function
- Large “1/dt” β higher throughput
π Both together give a complete picture
-
AuthorPosts
- You must be logged in to reply to this topic.
