An optimization that failed validation: evaluating speed across the whole path

Compare two weather representations using identical data. A smaller file loses 6,000 zeros, making reader equivalence more important than a lower median time.

A shorter path cannot deliver the intended result when part of the route is missing.
A shorter path cannot deliver the intended result when part of the route is missing.

A smaller weather file does not yet mean a better import. The file may shrink because the program encodes the same values more efficiently. It may also shrink because some values disappear. Both variants can produce attractive time and memory figures, while delivering different results to the reader.

In the independent teaching experiment below, the candidate wrote a gzip file roughly half the size and had a lower median duration for the entire local path. After reading, however, it turned 6,000 present zero values into missing data. That is why the change was rejected. The performance figures were preserved, but they did not become an argument for an incorrect result.

The experiment ran on Linux with Python 3.12.14, using fictional weather values. It follows the path from a local input file to a validated reader result. This is a completed example of evaluating a change, rather than a measurement of a production weather server or forecast quality.

Define what must remain equal first

The input contains 500 fictional cells, 24 relative hours, and two instantaneous fields: temperature in degrees Celsius and wind speed in metres per second. This gives 24,000 positions. The cells are not real cities, and the value sequence was created specifically for the experiment.

Each combination of cell, hour, and field requires one observable value or an explicit gap. Zero temperature, zero wind speed, and null have different meanings. Negative temperature is allowed; negative wind speed is rejected by this teaching contract.

Example value What the reader must receive
0.0 for temperature A present value of 0 °C
0.0 for wind speed A present value of 0 m/s
-3.0 for temperature A present negative value
null A missing value

Position identities, units, values, and missingness form the comparison contract. An equal row count is insufficient on its own. Likewise, an allowed change to the file representation does not permit a change in what the reader returns.

The full dataset contains 6,000 zeros, 6,000 missing values, and 12,000 other numeric values. Both variants receive the exact same 1,337,720 input bytes. Their identity is checked for every run.

An appealing idea and a short, incorrect filter

The baseline representation stores every position, including null. The candidate uses a sparse representation: it writes only present values, and the reader reconstructs omitted positions from the cell, hour, and field description. The idea itself is compatible with the contract, provided zero is not confused with absence.

A typical defect was deliberately introduced into the candidate:

selected = [row for row in rows if row["value"]]

In Python, numeric zero and None are false in a Boolean test. This is specified in the truth value testing documentation. The filter removes both cases even though our contract distinguishes them. Negative temperature remains, so a few ordinary nonzero examples could easily hide the defect.

The reader cannot recover the lost zero. It sees an omitted record and returns null, as the sparse format requires. It has no way to guess whether the writer omitted a truly missing value or accidentally removed a present one. The error happened before reading.

Measure the path to the reader

Both variants perform the same stages: reading JSONL, parsing and validating the input, preparing the representation, serializing JSON, compressing with gzip, writing a local file, reading it again, decompressing it, and validating the expanded result. The nested representation preparation stage is also timed separately.

The outer interval starts before reading the input bytes and ends after validating and expanding the reader response. Fixture creation, interpreter startup, final comparison with the expectation, checksum calculation, and report formatting are outside this interval. This is the declared measurement boundary, rather than the entire lifetime of the process.

Elapsed time is obtained through perf_counter_ns(), and CPU time for the current process through process_time_ns(). These metrics have different semantics, described in the time documentation. The nested preparation duration is not added to the outer duration: it is already included.

Memory is observed through resource.getrusage(RUSAGE_SELF).ru_maxrss. On Linux, this is the maximum resident set size used, in KiB; it belongs to the process rather than an individual function. The definitions appear in Python resource and Linux getrusage(2). It is read after the measured path, before the final comparison; interpreter startup is already included in that peak.

Compression uses the same explicit level 6 and mtime=0. The latter removes changing creation times from the gzip header; its purpose is described in the gzip documentation. Result equivalence is still checked after decompression: different valid representations can have different bytes.

Three paired runs, with every observation preserved

Three sequential pairs were executed: baseline → candidate, candidate → baseline, baseline → candidate. Each variant in each pair runs in a fresh child process. That makes six processes; the scenario contains no deliberate delays, parallel load, or selection of only the best results.

The operating system cache was not cleared. A new process does not make disk reads reliably cold. There are no separate warmup repetitions either. Ordinary file writes and reads pass through the operating system; fsync is not called, so the measurement does not describe guaranteed persistence after power loss.

Metric Baseline representation Candidate
Complete local path, median 250.363 ms 232.609 ms
Complete path, minimum–maximum 208.438–272.693 ms 153.888–236.030 ms
Complete path CPU, median 250.309 ms 231.574 ms
Nested preparation, median 3.732 ms 4.410 ms
Peak process RSS, median 42,608 KiB 35,952 KiB
Serialized JSON 1,337,853 bytes 667,494 bytes
Gzip file 82,650 bytes 39,997 bytes

The candidate has a lower median for the entire path, while its nested preparation is slower in this series. That is precisely why a result for one inner stage cannot be extended to the entire process. The difference occurs along a path that also serializes, compresses, writes, and reads different amounts of data.

The ranges of the three observations overlap. Such a short experiment does not provide a reliable speedup estimate for other runs, other hardware, or production workloads. These medians describe the preserved series itself. The decision to reject the candidate does not depend on whether it happens to be faster in the next run.

An equal position count concealed lost values

After expansion, both readers returned 24,000 positions. Format, units, and allowed keys passed structural validation. Comparing every position with its original value revealed a different picture:

Reader observation Baseline Candidate
Total positions 24,000 24,000
Present zeros 6,000 0
Missing values 6,000 12,000
Differences from the input 0 6,000

The result repeated in all three pairs. The candidate wrote only 12,000 nonzero numeric rows. The baseline wrote all 24,000. The smaller file was partly the result of retaining less useful information, so its size cannot be presented as a benefit of a compatible optimization.

For a real representation change, expectations should be defined at the boundary visible to the consumer. If the contract promises values, units, spatial position, time, and missingness, those are what must be compared. Equal message counts or successful decompression are only supporting checks.

A small example explains the defect better than a large percentage

A separate literal sample contains one cell, four hours, and two fields: eight positions. The expected values are written explicitly, independently of the large dataset generator. They include zero, missingness, a positive value, and negative temperature. The baseline path matches this sample; the candidate changes two zero positions.

The local suite of 27 test methods also checks duplicates, a missing dense position, an incorrect unit, an unknown field, Boolean or nonnumeric values, infinity, and corrupt gzip. These checks were executed. They complement the six measured processes, but do not become 27 independent performance measurements.

The precise filter correction is:

selected = [row for row in rows if row["value"] is not None]

A small control test using this filter restored all eight expected positions. The full large experiment for the corrected candidate has not been executed here. Its time and memory figures cannot be borrowed from the incorrect variant: the writer will now retain additional zeros, changing the amount of work in later stages.

Scope of the local experiment

The local check used the Python standard library.

The collector creates one deterministic input, runs three pairs, preserves each process output, and produces a summary. The large temporary input and output files are removed after the experiment; the recipe, checksums, sizes, and individual observations remain. This scenario requires Linux for its memory measurement so that ru_maxrss has the stated units.

Before taking the idea to a weather service, define that service’s actual final result separately. It may include downloading, GRIB decoding, persisting a revision, activation, and reading a page. The local JSON/gzip example does not perform those stages. Adding them to a new measurement boundary will change both the cost and the possible failure points.

A decision that survives the next run

For this candidate, a concrete record is enough: the input is identical; the file representation differs; the reader receives 6,000 additional missing values; the change is rejected because it violates the contract. Lower time, RSS, or byte counts do not remove that reason.

The next step is to preserve zeros correctly, repeat the entire declared path, and consider resource tradeoffs only after the results are equivalent. Speed will then have a clear object: the same useful forecast obtained at a different cost. Without that condition, the faster operation may simply be a different, incomplete task.

  1. Weather From a new model release to the page: measuring the whole weather cycle
  2. Weather The process finished, but was the whole forecast updated?
  3. Weather One weather contract for Go and PHP: checking data across the language boundary
  4. Weather One weather field for thousands of cities: batch reading and decoding

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article