Back to Explore
GuideVibeFix editorialUpdated Nov 24, 2026

Python Profiling in Practice: Measure First, Don't Optimize by Feel

When AI-generated code runs slow, guessing where to fix it usually fixes the wrong place. With 2000 reading records: concat takes 0.008 s over 20 runs, one extra reference makes it 0.544 s, and dict lookup is 417.4x faster than linear search — cProfile to locate, timeit to compare, Python 3.12.3 stdlib only.

Real photo: a laptop screen showing a code editor, with a small orange octopus plush toy beside it

The most common flaw in AI-generated code is not that it is wrong, it is that it is slow: a loop that builds a report, a lookup repeated inside another loop, and suddenly you are waiting. The least useful response is to rewrite by feel — “string concatenation must be the slow part”, “just switch to another style” — and then find nothing changed, because the real bottleneck never moved. The right move is to measure first: use cProfile to find where the time goes, and timeit to compare two ways of writing the same thing. Both are in the Python standard library, nothing to install. This guide demos with a fictional set of 2000 reading records, titled “Note-0001” through “Note-2000”, each with 30 to 89 minutes, and the lookup target is the second-to-last one, “Note-1999”, at 49 minutes. The demo script is rerun_en_demo248_g1.py, run on Python 3.12.3; the Chinese version is demo248_zh.py. The structure and the conclusions match, but the timings are from each run on its own, so the seconds quoted in the Chinese and English texts differ — each matches its own transcript.

Here is the conclusion up front, because it runs against intuition: the place that looks like the bottleneck is not slow at all, and the place that is actually slow is hard to spot by eye. Building a report from 2000 records, out = out + ... takes 0.008 seconds over 20 runs, and "".join takes 0.008 seconds over 20 runs — a speed ratio of 1.0x, effectively no difference. But the same concatenation code, holding one extra reference to the old string at each step, takes 0.544 seconds over 20 runs, 66.9x slower than join. And searching 2000 titles for “Note-1999”: a linear search takes 0.428 seconds over 10000 runs, a dict lookup takes 0.001 seconds, so the dict is 417.4x faster. In short: measure before you optimize, and you will find the thing to change is the lookup, not the concatenation.

Two tools, two questions

cProfile and timeit often get mixed up, but they answer two different questions. cProfile answers “which functions ate the time”: it examines a whole run and tells you how many times each function was called and how much time accumulated there, which is what you want when you only know “the whole thing is slow” and not where. timeit answers “which of these two ways of writing it is faster”: it times one small snippet over many runs and gives you a trustworthy number, which is what you want once you have a suspect and want to compare spellings. The order matters: comparing spellings before locating the problem is guessing, and rewriting before comparing is gambling.

The official docs put it plainly. cProfile is a deterministic profiler: it watches every function call, return, and exception, and gives exact call-count statistics. Call counts can expose bugs (a surprising count), internal time can expose “hot loops”, and cumulative time can expose high-level mistakes such as picking the wrong algorithm. The timeit docs say the module times small bits of code while avoiding common measurement traps; its default timer is time.perf_counter(), and it switches garbage collection off during timing so repeated measurements are easier to compare. Once you remember this split, every step below knows what it is doing.

One more warning about the split, from something the demo actually hit: keep locating and timing separate, do not nest them. Running the demo on its own, join over 20 runs took 0.009 seconds and dict lookup over 10000 runs took 0.001 seconds in the Chinese run; wrapping the same code in python -m cProfile and running it again, join grew to 0.015 seconds and dict lookup to 0.007 seconds. The code did not get slower — the profiler adds overhead to every function call it watches, and the more calls it watches, the more overhead it adds. So the rule is: turn the profiler on to find the bottleneck, turn it off to compare speeds, and let each tool do its own job.

timeit test 1: concatenation is not as slow as you think

Section 1 of the demo tests the usual suspect: string concatenation. Plenty of tutorials say “+ in a loop is slow, always use join”, and AI-generated code is full of out = out + ..., which looks like the first thing to fix. The measured result: building a report from 2000 records, out = out + ... over 20 runs took 0.008 seconds, join over 20 runs took 0.008 seconds, a ratio of 1.0x. The two reports are identical in content, both 42000 characters, so changing the spelling saves no time at all, and this suspect can be cleared.

Why? Because CPython has an in-place optimization here: when a string has only one reference, concatenation can resize it in place instead of copying a new string every time. In the demo, out has exactly one reference inside the loop, so the optimization applies and out = out + ... runs as fast as join. That is not a guess — the second half of section 1 proves it. The same concatenation code, keeping one extra reference to the old string at each step so the string is no longer the only reference, jumps from 0.008 seconds to 0.544 seconds over 20 runs, 66.9x slower than join. Not one line of code changed, only one extra reference, and the speed differs by almost seventy times. That is the danger of optimizing by feel: the thing you think is slow, and the thing that actually is slow, are not the same thing.

Take this as a standing rule: before you believe any claim of the form “this spelling is always slow”, including claims in this guide, run timeit on your own machine with your own data. A new CPython version, a different data size, a different reference pattern, and the conclusion can flip. The demo numbers come from Python 3.12.3 with 2000 records; whether your project has 200 records or 2 million, the result may be completely different, and the only reliable way to know is to time your own code. One more detail: timeit.timeit takes a number argument — the demo uses number=20 for concatenation, meaning the whole build runs 20 times before the total is reported, not once. A single run takes about 0.0004 seconds, far too jittery to compare.

timeit test 2: the real bottleneck is the lookup

Section 2 tests something else: finding “Note-1999” among 2000 titles. A linear search, comparing one title after another, takes 0.428 seconds over 10000 runs; a dict lookup, going straight to the title, takes 0.001 seconds, 417.4x faster. Put the two sections side by side and the priority is obvious: the 0.008 seconds of concatenation is not worth touching, the 0.428 seconds of lookup is the bulk of the time, and the fix is not a spelling tweak but a change of algorithm — turn the list into a dict, and lookup goes from comparing one by one to going straight there.

One detail is worth noting: the demo searches for “Note-1999”, the second-to-last record, which is almost the worst case for a linear search — it has to compare 1999 titles before it hits. Searching for the first record, “Note-0001”, would match on the first comparison, the two numbers would be close, and the conclusion would change with them. So when you set up a comparison, pick test data that represents the real case: the worst case, the most common case, not just the case that flatters your preferred answer. The demo deliberately picked a target near the end so the gap between the two spellings shows up in full. That is basic timeit craft: decide what scenario you are comparing, then run the numbers.

Put the two tests together and the order of work writes itself: change the algorithm first, then the spelling. Swapping the algorithm takes the lookup from 0.428 seconds to 0.001 seconds, saving more than 99%; swapping the spelling leaves 0.008 seconds at 0.008 seconds, saving zero. The most common performance flaw in AI-generated code is exactly this shape — a spelling that looks clumsy while the algorithm is the real problem: checking membership in a list inside a loop, recomputing something that never changes, looking a value up inside a nested loop. Those costs scale by multiples, and the time saved by fixing one line of concatenation is not even a rounding error next to them. Next time something “must be slow”, ask first: is it the spelling that is slow, or the method?

repeat: trust only the minimum

Section 3 covers a place where timeit is easy to misuse: believing a single run. The demo uses repeat to time the join build of 20 runs five times over, getting 0.007, 0.007, 0.007, 0.008, 0.007 seconds, with a minimum of 0.007 seconds. The five runs agree because the machine was idle and the code is steady, but that is not the norm: another process grabbing the CPU, or garbage collection kicking in, can make one run suddenly larger. The official docs are explicit about this: do not average the five numbers or compute a standard deviation, because the larger values are usually not your code getting slower but other processes interfering with the timing. Take the minimum — it is the fastest your machine can run this code, the true lower bound.

This advice feels backwards, so it is worth a second sentence. In most experiments we average to “cancel out error”, but timing is not most experiments: interference can only make a run longer, never shorter, so the minimum is closest to the truth and the average folds the interference in. In the demo the five runs are 0.007, 0.007, 0.007, 0.008, 0.007, so the minimum and the average barely differ — but that is luck. Let one run be disturbed, say 0.007, 0.009, 0.007, 0.021, 0.007, and the average is dragged up by the 0.021 while the minimum stays 0.007. Remember this: after timeit.repeat, look at min(), and use the rest only to judge whether the machine was steady.

Two timeit defaults are worth knowing so they do not catch you out. First, garbage collection is switched off during timing, so that repeated measurements are easier to compare; if your code produces a lot of garbage, real runs pay collection time that the measurement hides, and you can switch it back on in setup with gc.enable() when that matters. Second, the command line python -m timeit picks a suitable loop count for you, while the function call defaults number to 1000000 — one million runs — which will run forever on slow code unless you pass number yourself. The demo passes 20 for concatenation and 10000 for lookup, chosen by hand for how fast each piece is. Get into that habit.

cProfile: read the call counts first, then the times

Section 4 is the cProfile part. Running the whole run_report once, the profiler recorded 6009 function calls. Line by line: run_report itself was called once, cumulative 0.005 seconds; parse_entry was called 2000 times, cumulative 0.002 seconds; build_report_slow was called once, cumulative 0.000 seconds; build_report_fast was called once, cumulative 0.001 seconds; find_slow and find_fast were each called once, cumulative 0.000 seconds. The order you read this table matters: look at the call counts first, then the times, because the counts are clues on their own.

The docs say it directly: call-count statistics can expose bugs, and a surprising count is surprising behavior. parse_entry being called 2000 times is exactly the record count, which is what you expect; if it had been called 4000 times, you would know the same records were parsed twice somewhere, without even looking at the time. The total of 6009 also adds up: 2000 parses, plus 2000 split calls, 2001 generator-expression evaluations, plus a handful of single calls for building the reports and the lookups. The total is the same on any machine, because call counts do not depend on how fast the machine is, only on which paths the code took. That is the most reliable part of cProfile: times wobble, counts do not.

Then the two time columns, which are two different ideas — do not mix them up. Cumulative time is “this function plus everything it called, all together”; internal time is “just this function’s own code, not the people it called”. run_report has a cumulative time of 0.005 seconds because it includes parsing, building, and searching; parse_entry has a cumulative time of 0.002 seconds, the largest share, because it was called 2000 times and a little each time adds up. When you are locating a bottleneck, cumulative time finds “which call chain is most expensive” and internal time finds “which piece of code is most expensive on its own”; read the two together and you know which line to touch. The demo is small, so the absolute numbers are tiny, but the way to read the table is the same at any scale.

You can also run the profiler from the command line without changing code: python -m cProfile -s cumulative demo248_zh.py, where -s cumulative sorts by cumulative time so the most expensive call chain comes first. The demo script uses the programmatic form instead — cProfile.Profile(), enable(), disable(), then pstats.Stats to pull the numbers out and print them in a controlled format, which is how the transcript was produced. Both do the same thing; pick by habit: the command line for a quick look, the programmatic form when you want the result written into a report or a fixed workflow.

Bar chart: English rerun measurements, concat over 20 runs 0.008 seconds, 0.008 seconds, 0.544 seconds; lookup over 10000 runs linear search 0.428 seconds, dict lookup 0.001 seconds

The chart above shows both comparisons at a glance, with numbers matching the English transcript exactly. On the left, three bars: the first two hug the ground at 0.008 seconds each, and the third shoots up to 0.544 seconds — one glance shows how serious “one extra reference” is. On the right, two bars: linear search at 0.428 seconds, dict lookup at 0.001 seconds, almost invisible, a gap of 417.4x. Together they are the core conclusion of this guide: the optimization you guessed (concatenation) is not worth touching, and the real bottleneck (the lookup method) is fixed by changing the algorithm. Next time someone says “this code must be slow”, run a chart like this first, then decide which line to touch.

The order of work: locate, compare, then change

Here is the fixed order to follow next time something in a vibe project feels “a bit slow”. First, locate: run the whole flow under cProfile, check whether any call count looks wrong, and find which call chain holds the most cumulative time — write down “where it is slow” before thinking about “how to fix it”. Second, compare: for the suspect lines, use timeit to compare two or more spellings, run repeat five times and take the minimum, write the numbers down, and run them again after the change to confirm it really got faster. Third, change: swap the algorithm first (a list for a dict, say), then the spelling (a different way to build a string), one change at a time with a measurement after each, never five changes at once where you cannot tell which one helped.

Three red lines to remember. First, do not turn cProfile on in production: it adds overhead to every call, slow programs get slower, and it records deterministic data rather than samples, so a long run produces a large statistics file — locating problems live calls for a sampling profiler, a different topic. Second, do not draw conclusions from one measurement on one machine: timings depend on the machine, the data size, and the load at the time. The Chinese and English runs of the same demo gave different numbers (the Chinese run’s extra-reference concatenation was 0.703 seconds and 81.7x, its linear search 0.374 seconds and the dict 379.8x faster) — the conclusions agree, the numbers do not, and that is normal for timing. Third, optimization has an end: no user can feel the difference in a place that takes 0.001 seconds, and the time is better spent fixing bugs and writing tests. Know when to stop.

Checklist and boundaries

Collect the method into a checklist: when something feels slow, run cProfile to locate it, watching for surprising call counts and the most expensive call chain; once you have a suspect, compare spellings with timeit, picking number by hand for how fast the code is, running repeat five times and taking the minimum; change the algorithm before the spelling, one change at a time with a measurement after each, and re-run to confirm; keep locating and timing apart, never nested; and remember that numbers only mean something on your own machine and data, so write down the scale you measured at.

Finally, what this guide does not cover, so you do not take these two tools into fights they cannot win: it does not cover sampling profilers — locating problems live and in long-running programs is a separate method; it does not cover concurrency and async performance — the site’s asyncio and concurrency guides cover waiting and parallelism, where “slow” often means waiting rather than computing, and the cProfile table reads differently there; it does not cover logging — the site’s logging guide is about “what happened while the program ran”, while this guide is about “where the time went”, one is events and the other is cost, use them together rather than as substitutes; and it does not cover load testing or capacity planning, which is a separate flow before launch. One more boundary note: this guide continues the site’s Python basics series — the dataclasses guide covers how to organize data, the typing guide covers annotations, and this one covers what to do after the code runs: find the slow parts and prove the fix actually made it faster.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles