Google Benchmark
raw JSON → 1.9.5 verified Mon Apr 27 auth: no python
A Python library to benchmark code snippets, wrapping the C++ Google Benchmark library. Version 1.9.5 requires Python >=3.10 and provides a simple API for timing code execution and comparing performance.
pip install google-benchmark Common errors
error ModuleNotFoundError: No module named 'benchmark' ↓
cause Trying to import 'benchmark' but the module is installed as 'google_benchmark' (package name: google-benchmark).
fix
Install the correct package: pip install google-benchmark, then import as import google_benchmark as benchmark.
error AttributeError: module 'benchmark' has no attribute 'register' ↓
cause The 'benchmark' module is the old package (benchmark) installed, not google_benchmark.
fix
Uninstall the old package (pip uninstall benchmark) and install google-benchmark (pip install google-benchmark). Then use import google_benchmark as benchmark.
error TypeError: my_benchmark() takes 0 positional arguments but 1 was given ↓
cause Benchmark function does not accept the state argument.
fix
Add state parameter: def my_benchmark(state): and use for _ in state: inside.
Warnings
breaking In google-benchmark >=1.9.0, the module name changed from 'benchmark' to 'google_benchmark'. Older code using 'import benchmark' will break. ↓
fix Replace 'import benchmark' with 'import google_benchmark as benchmark'.
gotcha Using `for _ in state:` is required to iterate the number of times determined by the framework. Forgetting this loop will cause the benchmark to run only once and produce incorrect results. ↓
fix Always include 'for _ in state:' inside your benchmark function.
gotcha The `state` object must be passed as the first argument to the benchmark function. Changing the argument name is fine, but omitting it or using a different signature will raise a TypeError. ↓
fix Ensure your benchmark function accepts exactly one argument (the state object).
deprecated The 'SetUp' and 'TearDown' methods via subclassing have been deprecated in favor of fixture decorators (not yet available). Check official docs for alternatives. ↓
fix Use register with custom setup/teardown inside the benchmark function or wait for new fixture API.
Imports
- benchmark wrong
import benchmarkcorrectimport google_benchmark as benchmark
Quickstart
import google_benchmark as benchmark
import os
@benchmark.register
def my_benchmark(state):
x = int(os.environ.get('SIZE', '1000'))
for _ in state:
sum(i*i for i in range(x))
if __name__ == '__main__':
benchmark.main()