Speed Up a Slow Function with Big-O Analysis and a Benchmark

You get the exact bottleneck line, current vs. proposed Big-O, an optimized drop-in function, and a small benchmark that proves the speedup before you adopt it.

Prompt

Prompt
Act as a senior performance engineer who reviews code for speed problems.

I will paste a slow function right after this message, with its language and how it is called. If I leave out the typical input size or how the function is used, ask me up to 3 short numbered questions in one message and wait for my answers before you start.

Rules:
1. State the current and proposed time complexity in Big-O, and define every variable you use (for example, n = number of orders).
2. Quote the exact line or lines causing the bottleneck and explain in one or two sentences why they are slow.
3. Keep behavior identical: same outputs, same ordering, same edge cases. If any change alters behavior, say so plainly.
4. Prefer the standard library before adding dependencies.
5. Give a small, self-contained benchmark that runs both versions on realistic input sizes and asserts they return the same result.

Output format:
1. Bottleneck: quoted line plus explanation
2. Complexity: table with columns Version, Time, Space, Notes
3. Optimized code: full function, with short comments on changed lines
4. Benchmark: runnable snippet and how to run it
5. Expected gain: rough estimate, labeled as an estimate until I run the benchmark

End with one line on assumptions you made and any risks, such as higher memory use or input cases the benchmark does not cover.

Example output

At a glanceCurrent vs proposed repeat-buyer functionComplexity from the example's analysis table
ItemCurrentProposed
Time complexityO(n²)O(n)
Space complexityO(n)O(u)
ApproachSlice and scan remaining ordersTwo passes with hashing
Membership checkLinear scan of result listO(1) set lookup
At 5,000 orders (estimate)Roughly 1 to 2 secondsA few milliseconds

Example for: a Python function that finds repeat customer emails in a list of about 50,000 orders; output order must match first appearance.

1. Bottleneck
for other in orders[i + 1:]:

For every order, this slices and scans all remaining orders, so comparisons grow with the square of the list. The check order["email"] not in repeat adds a linear scan of the result list on every match.

2. Complexity
VersionTimeSpaceNotes
CurrentO(n²)O(n)n = orders; each slice copies up to n items
ProposedO(n)O(u)u = unique emails; two passes with hashing
3. Optimized code
from collections import Counter

def find_repeat_buyers(orders):
    # One pass to count every email
    counts = Counter(order["email"] for order in orders)
    added = set()  # O(1) membership instead of scanning a list
    repeat = []
    # Second pass keeps first-appearance order, same as the original
    for order in orders:
        email = order["email"]
        if counts[email] > 1 and email not in added:
            repeat.append(email)
            added.add(email)
    return repeat
4. Benchmark

Save as bench.py with both versions renamed old_version and new_version, then run python bench.py.

import random
import timeit

random.seed(42)
orders = [dict(email="user" + str(random.randint(0, 3000)) + "@shop.test")
          for _ in range(5000)]

assert old_version(orders) == new_version(orders), "Outputs differ"

for name, fn in [("old", old_version), ("new", new_version)]:
    total = timeit.timeit(lambda: fn(orders), number=3)
    print(name, round(total / 3, 4), "seconds per call")

Try 5,000 first, then 50,000 orders for the new version only; the old one may take minutes at that size.

5. Expected gain

Estimate: at 5,000 orders the old version does about 12.5 million comparisons (roughly 1 to 2 seconds), while the new one finishes in a few milliseconds. At 50,000 orders the gap widens about 100x because the old cost grows quadratically. Confirm with the benchmark before merging.

Assumptions and risks: Emails are compared exactly as stored (no lowercasing or trimming, matching the original); memory rises slightly for the Counter, and the benchmark does not cover orders missing an "email" key.

Written by AI from this prompt. Your results will vary.

Tips and common edits

Why this works

  • Requiring the exact bottleneck line forces a real diagnosis instead of generic tips like 'use a set'.
  • The behavior-identical rule catches subtle breaks such as changed output order or edge cases.
  • An asserting benchmark lets you verify the speedup and correctness yourself before trusting the estimate.

Use when a function is noticeably slow on real data. Paste the full function into ChatGPT, Claude or Gemini, and note the language, typical input size, and whether output order matters.

Common edits

  • Add a memory limit, e.g. 'the input may not fit in RAM', to get streaming-friendly suggestions.
  • Ask for two options: a quick fix and a deeper rewrite, with tradeoffs for each.

Prompt details

By
Prompts-GPT editors
Published
How prompts are written and checked

Did this prompt work?

Keep exploring

More in Coding