Saving timeit Output in Python 2026 with Efficient Code

Efficient Code Mar 15, 2026

Saving timeit Output in Python 2026 with Efficient Code

Running timeit benchmarks is useful, but saving the results is essential for tracking performance improvements over time. In 2026, properly saving and comparing timeit output helps you maintain a history of optimizations and make data-driven decisions.

This March 15, 2026 guide shows modern ways to save, store, and analyze timeit results effectively.

TL;DR — Key Takeaways 2026

  • Save timeit results to compare performance before and after changes
  • Use JSON, CSV, or Markdown for easy tracking
  • Automate saving with a reusable benchmark function
  • Include metadata (date, Python version, hardware) for context
  • Free-threading and faster runtimes make consistent saving even more important

1. Simple Way to Save timeit Output


import timeit
import json
import platform
from datetime import datetime

def benchmark_and_save(name, stmt, setup="", number=1000, repeat=7):
    timer = timeit.Timer(stmt=stmt, setup=setup)
    times = timer.repeat(repeat=repeat, number=number)
    best = min(times) / number
    
    result = {
        "test_name": name,
        "best_time_per_loop": best,
        "unit": "seconds",
        "number_of_loops": number,
        "repeats": repeat,
        "timestamp": datetime.now().isoformat(),
        "python_version": platform.python_version()
    }
    
    # Save to JSON
    with open("benchmarks.json", "a") as f:
        f.write(json.dumps(result) + "\n")
    
    print(f"{name}: {best*1_000_000:.2f} µs per loop")
    return best

# Usage
benchmark_and_save("sum_range", "sum(range(100000))")
benchmark_and_save("numpy_sum", 
                   "np.sum(arr**2)", 
                   setup="import numpy as np; arr = np.arange(100000)")

2. Saving to CSV for Easy Comparison


import csv
from datetime import datetime

def save_to_csv(name, best_time):
    with open("benchmarks.csv", "a", newline="") as f:
        writer = csv.writer(f)
        writer.writerow([
            datetime.now().strftime("%Y-%m-%d %H:%M"),
            name,
            f"{best_time*1_000_000:.2f}",
            "µs per loop"
        ])

# Usage after benchmark
save_to_csv("List Comprehension", 1245.67)
save_to_csv("NumPy Vectorized",  45.32)

3. Best Practices for Saving timeit Results in 2026

  • Always save before and after any optimization
  • Include timestamp and environment info (Python version, hardware)
  • Use JSON for structured data or CSV for easy spreadsheets
  • Automate saving with a helper function
  • Version your benchmark files (e.g., benchmarks_v2.json)

Why Save Benchmark Results

Timing results are only useful over time if they are recorded. Saving each measurement with a timestamp, environment details and the exact statement lets you see whether a change made code faster and spot slowdowns early.

Append-only formats such as JSON Lines or CSV are ideal: each run adds one line, older results are never overwritten, and pandas can load the file for comparison.

Record the Python version and machine name, because timings are only comparable within the same environment.

Worked Example: Logging and Comparing Runs

Benchmarks are appended to a JSON Lines file and summarised with pandas.

import json
import platform
import timeit
from datetime import datetime

import pandas as pd

def record(name, stmt, setup="", path="bench.jsonl"):
    best = min(timeit.repeat(stmt, setup=setup, number=200, repeat=5)) / 200
    row = {"name": name, "seconds": best, "python": platform.python_version(),
           "machine": platform.node(), "at": datetime.now().isoformat(timespec="seconds")}
    with open(path, "a", encoding="utf-8") as f:
        f.write(json.dumps(row) + "\n")
    return best

record("list_sum", "sum(data)", setup="data = list(range(10_000))")
record("list_sum", "sum(data)", setup="data = list(range(10_000))")
record("set_build", "set(data)", setup="data = list(range(10_000))")

log = pd.read_json("bench.jsonl", lines=True)
print(log.groupby("name")["seconds"].agg(["count", "min"]))

Each call appends one line, so the log keeps growing across runs. pandas reads the JSON Lines file directly, and grouping by name shows how many measurements exist and the best time for each.

Practical Tips

CSV is a good alternative when results will be opened in a spreadsheet. Use the csv module with a header row, and write the header only when the file does not exist yet, so repeated runs keep adding rows under the same columns.

Keep the benchmark statements under version control next to the results file. When numbers change, you can then check whether the code, the input size or the environment changed, instead of guessing.

Common Mistakes

  • Overwriting previous results each run.
  • Saving times without units or environment details.
  • Comparing results from different machines.
  • Writing literal newlines incorrectly inside strings.

Quick Summary

  • Append results with timestamps.
  • Use JSON Lines or CSV.
  • Record Python version and machine.
  • Load logs with pandas to compare runs.

Conclusion — Saving timeit Output in 2026

Saving timeit results is a key part of a professional performance workflow. In 2026, developers who consistently record and compare benchmarks can track improvements over time, avoid regression, and make confident optimization decisions. Make saving your timeit results a habit — it pays off quickly.

Next steps:

  • Create a reusable benchmark_and_save() function for your projects

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices