### Per-kernel setup functions in perfplot.show() Source: https://context7.com/nschloe/perfplot/llms.txt When kernels require different input preparation, pass a list of setup functions to perfplot.show(). The example shows one kernel using a Python list and another using a NumPy array. Set equality_check=None when inputs differ. ```python import numpy as np import perfplot perfplot.show( setup=[ lambda n: list(range(n)), # Python list for kernel 0 lambda n: np.arange(n), # NumPy array for kernel 1 ], kernels=[ lambda lst: sum(lst), lambda arr: np.sum(arr), ], labels=["sum(list)", "np.sum(array)"], n_range=[2**k for k in range(18)], xlabel="len", equality_check=None, # inputs differ, outputs may not be comparable ) ``` -------------------------------- ### Per-kernel setup — Using a list of setup functions Source: https://context7.com/nschloe/perfplot/llms.txt When different kernels require different input preparation (e.g., one uses a Python list and another uses a NumPy array), pass a list of setup functions instead of a single callable. ```APIDOC ## Per-kernel setup — Using a list of setup functions When different kernels require different input preparation (e.g., one uses a Python list and another uses a NumPy array), pass a list of setup functions instead of a single callable. ```python import numpy as np import perfplot perfplot.show( setup=[ lambda n: list(range(n)), # Python list for kernel 0 lambda n: np.arange(n), # NumPy array for kernel 1 ], kernels=[ lambda lst: sum(lst), lambda arr: np.sum(arr), ], labels=["sum(list)", "np.sum(array)"], n_range=[2**k for k in range(18)], xlabel="len", equality_check=None, # inputs differ, outputs may not be comparable ) ``` ``` -------------------------------- ### Install Perfplot using pip Source: https://github.com/nschloe/perfplot/blob/main/README.md Installs the perfplot library using pip. This is the standard method for installing Python packages. ```bash pip install perfplot ``` -------------------------------- ### Benchmark and Display Plot Interactively with perfplot.show() Source: https://context7.com/nschloe/perfplot/llms.txt Use `perfplot.show()` to run kernels across a range of input sizes and immediately display an interactive matplotlib plot. It accepts arguments for setup, kernels, labels, input ranges, axis scaling, time units, and correctness checks. ```python import numpy as np import perfplot perfplot.show( setup=lambda n: np.random.rand(n), # generates input data for each n kernels=[ lambda a: np.c_[a, a], lambda a: np.stack([a, a]).T, lambda a: np.vstack([a, a]).T, lambda a: np.column_stack([a, a]), lambda a: np.concatenate([a[:, None], a[:, None]], axis=1), ], labels=["c_", "stack", "vstack", "column_stack", "concat"], n_range=[2**k for k in range(25)], xlabel="len(a)", logx="auto", # auto-detect log scale (default) logy="auto", # auto-detect log scale (default) time_unit="s", # "auto", "s", "ms", "us", or "ns" relative_to=None, # set to an int index to plot relative timings equality_check=np.allclose, # set to None to skip correctness check show_progress=True, target_time_per_measurement=1.0, # seconds per n value max_time=None, # skip a kernel once it exceeds this time (seconds) ) ``` -------------------------------- ### FLOPS benchmarking with perfplot.show() Source: https://context7.com/nschloe/perfplot/llms.txt Measure computational throughput by providing a 'flops' callable to perfplot.show(). This plots floating-point operations per second instead of raw runtimes. The example demonstrates matrix-vector multiplication, where FLOPs are 2*n^2. ```python import numpy as np import perfplot # Matrix-vector multiply: 2*n^2 FLOPs perfplot.show( setup=lambda n: (np.random.rand(n, n), np.random.rand(n)), kernels=[ lambda A, x: A @ x, lambda A, x: np.dot(A, x), ], labels=["A @ x", "np.dot(A, x)"], n_range=[2**k for k in range(1, 11)], xlabel="matrix dimension n", flops=lambda n: 2 * n**2, equality_check=np.allclose, ) ``` -------------------------------- ### Compare NumPy Array Concatenation Methods Source: https://github.com/nschloe/perfplot/blob/main/README.md Compares different NumPy array concatenation methods by plotting their performance across a range of input sizes. Requires numpy and perfplot. The `setup` argument prepares the input data, and `kernels` contains the functions to benchmark. `n_range` specifies the input sizes to test. By default, it asserts the equality of outputs. ```python import numpy as np import perfplot perfplot.show( setup=lambda n: np.random.rand(n), # or setup=np.random.rand kernels=[ lambda a: np.c_[a, a], lambda a: np.stack([a, a]).T, lambda a: np.vstack([a, a]).T, lambda a: np.column_stack([a, a]), lambda a: np.concatenate([a[:, None], a[:, None]], axis=1), ], labels=["c_", "stack", "vstack", "column_stack", "concat"], n_range=[2**k for k in range(25)], xlabel="len(a)", # More optional arguments with their default values: # logx="auto", # set to True or False to force scaling # logy="auto", # equality_check=np.allclose, # set to None to disable "correctness" assertion # show_progress=True, # target_time_per_measurement=1.0, # max_time=None, # maximum time per measurement # time_unit="s", # set to one of ("auto", "s", "ms", "us", or "ns") to force plot units # relative_to=1, # plot the timings relative to one of the measurements # flops=lambda n: 3*n, # FLOPS plots ) ``` -------------------------------- ### Error handling with PerfplotError and equality checks Source: https://context7.com/nschloe/perfplot/llms.txt perfplot raises PerfplotError for unequal kernel outputs, indicating a potential bug. You can disable checking with equality_check=None or provide a custom comparator. The example demonstrates catching PerfplotError when a buggy sum function is used. ```python import numpy as np import perfplot from perfplot import PerfplotError def correct_sum(a): return np.sum(a) def buggy_sum(a): return np.sum(a) + 1.0 # intentionally wrong try: perfplot.bench( setup=np.random.rand, kernels=[correct_sum, buggy_sum], labels=["correct", "buggy"], n_range=[2**k for k in range(5)], equality_check=np.allclose, # will catch the discrepancy ) except PerfplotError as e: print(f"Caught PerfplotError: {e}") # → Equality check failure. # correct: ... # buggy: ... ``` -------------------------------- ### perfplot.show() Source: https://context7.com/nschloe/perfplot/llms.txt Runs all kernels across the full n_range, then immediately opens an interactive matplotlib window showing runtime vs. input size. Accepts all bench() arguments plus plot-related options. ```APIDOC ## perfplot.show() ### Description Runs all kernels across the full `n_range`, then immediately opens an interactive matplotlib window showing runtime vs. input size. Accepts all `bench()` arguments plus plot-related options (`time_unit`, `logx`, `logy`, `relative_to`). ### Parameters - `setup` (callable) - Function that generates input data for each value in `n_range`. - `kernels` (list of callables) - List of functions to benchmark. - `labels` (list of strings, optional) - Labels for each kernel in the plot. - `n_range` (list of ints) - Range of input sizes to benchmark. - `xlabel` (string, optional) - Label for the x-axis. - `logx` (string or bool, optional) - Whether to use a log scale for the x-axis. Defaults to 'auto'. - `logy` (string or bool, optional) - Whether to use a log scale for the y-axis. Defaults to 'auto'. - `time_unit` (string, optional) - Unit for time measurements ('auto', 's', 'ms', 'us', 'ns'). Defaults to 'auto'. - `relative_to` (int, optional) - Index of the kernel to use for relative timing comparisons. Defaults to None. - `equality_check` (callable, optional) - Function to check for equality of results. Defaults to `np.allclose`. - `show_progress` (bool, optional) - Whether to display a progress bar. Defaults to False. - `target_time_per_measurement` (float, optional) - Target time in seconds for each measurement. - `max_time` (float, optional) - Maximum time in seconds allowed for a single kernel measurement before skipping it. ### Request Example ```python import numpy as np import perfplot perfplot.show( setup=lambda n: np.random.rand(n), # generates input data for each n kernels=[ lambda a: np.c_[a, a], lambda a: np.stack([a, a]).T, lambda a: np.vstack([a, a]).T, lambda a: np.column_stack([a, a]), lambda a: np.concatenate([a[:, None], a[:, None]], axis=1), ], labels=["c_", "stack", "vstack", "column_stack", "concat"], n_range=[2**k for k in range(25)], xlabel="len(a)", logx="auto", # auto-detect log scale (default) logy="auto", # auto-detect log scale (default) time_unit="s", # "auto", "s", "ms", "us", or "ns" relative_to=None, # set to an int index to plot relative timings equality_check=np.allclose, # set to None to skip correctness check show_progress=True, target_time_per_measurement=1.0, # seconds per n value max_time=None, # skip a kernel once it exceeds this time (seconds) ) ``` ``` -------------------------------- ### Run Perfplot Unit Tests with Tox Source: https://github.com/nschloe/perfplot/blob/main/README.md Runs the unit tests for perfplot using tox. This command should be executed after checking out the repository. ```bash tox ``` -------------------------------- ### Live Plotting of Benchmark Results Source: https://github.com/nschloe/perfplot/blob/main/README.md Generates benchmark results and plots them live as they are computed. This is useful for long-running benchmarks. It accepts the same arguments as `perfplot.show()` except for plot-specific arguments. ```python perfplot.live( # ... ) ``` -------------------------------- ### Benchmark with Live-Updating Plot using perfplot.live() Source: https://context7.com/nschloe/perfplot/llms.txt Employ `perfplot.live()` to render a matplotlib animation that updates the plot in real time as measurements are taken. This is ideal for long-running benchmarks requiring immediate visual feedback. Configure `max_time` to skip kernels if a single measurement exceeds a specified duration. ```python import numpy as np import perfplot perfplot.live( setup=lambda n: np.random.rand(n), kernels=[ lambda a: list(a), lambda a: a.tolist(), ], labels=["list()", ".tolist()"], n_range=[2**k for k in range(22)], xlabel="len(a)", target_time_per_measurement=1.0, max_time=5.0, # skip kernel if a single measurement exceeds 5 s equality_check=None, show_progress=True, logx="auto", logy="auto", ) ``` -------------------------------- ### FLOPS benchmarking — Measuring computational throughput Source: https://context7.com/nschloe/perfplot/llms.txt When you know the theoretical FLOP count for each input size, pass a `flops` callable to `bench()` or `show()` to plot floating-point operations per second instead of raw runtimes. ```APIDOC ## FLOPS benchmarking — Measuring computational throughput When you know the theoretical FLOP count for each input size, pass a `flops` callable to `bench()` or `show()` to plot floating-point operations per second instead of raw runtimes. ```python import numpy as np import perfplot # Matrix-vector multiply: 2*n^2 FLOPs perfplot.show( setup=lambda n: (np.random.rand(n, n), np.random.rand(n)), kernels=[ lambda A, x: A @ x, lambda A, x: np.dot(A, x), ], labels=["A @ x", "np.dot(A, x)"], n_range=[2**k for k in range(1, 11)], xlabel="matrix dimension n", flops=lambda n: 2 * n**2, equality_check=np.allclose, ) ``` ``` -------------------------------- ### perfplot.bench() Source: https://context7.com/nschloe/perfplot/llms.txt Runs all kernels across n_range and returns a PerfplotData object. Separating benchmarking from plotting allows saving multiple plot formats, printing tabular results, or customizing the plot before display. ```APIDOC ## perfplot.bench() ### Description Runs all kernels across `n_range` and returns a `PerfplotData` object. Separating benchmarking from plotting allows saving multiple plot formats, printing tabular results, or customizing the plot before display. ### Parameters - `setup` (callable) - Function that generates input data for each value in `n_range`. - `kernels` (list of callables) - List of functions to benchmark. - `labels` (list of strings, optional) - Labels for each kernel. - `n_range` (list of ints) - Range of input sizes to benchmark. - `xlabel` (string, optional) - Label for the x-axis. - `title` (string, optional) - Title for the plot. - `target_time_per_measurement` (float, optional) - Target time in seconds for each measurement. - `equality_check` (callable, optional) - Function to check for equality of results. Defaults to `np.allclose`. - `show_progress` (bool, optional) - Whether to display a progress bar. Defaults to False. ### Returns - `PerfplotData` object - Contains benchmark results that can be used for plotting or analysis. ### Request Example ```python import numpy as np import perfplot def sort_builtin(a): return sorted(a) def sort_numpy(a): return np.sort(a) out = perfplot.bench( setup=lambda n: np.random.rand(n).tolist(), kernels=[sort_builtin, sort_numpy], labels=["sorted()", "np.sort()"], n_range=[2**k for k in range(20)], xlabel="len(a)", title="Sort comparison", target_time_per_measurement=1.0, equality_check=None, # outputs differ (list vs ndarray), skip check show_progress=True, ) # Print tabular results to stdout print(out) # Show interactive plot out.show(time_unit="ms") # Save to file with tight layout out.save("sort_comparison.png", transparent=True, bbox_inches="tight") # Save relative-to-first-kernel plot out.save("sort_relative.svg", relative_to=0) ``` ``` -------------------------------- ### Benchmark and Return Data Object with perfplot.bench() Source: https://context7.com/nschloe/perfplot/llms.txt Utilize `perfplot.bench()` to benchmark kernels and obtain a `PerfplotData` object, separating benchmarking from plotting for flexible output. This allows saving plots in various formats, printing tabular results, or customizing plots before display. The `equality_check` can be set to `None` if kernel outputs differ in type. ```python import numpy as np import perfplot def sort_builtin(a): return sorted(a) def sort_numpy(a): return np.sort(a) out = perfplot.bench( setup=lambda n: np.random.rand(n).tolist(), kernels=[sort_builtin, sort_numpy], labels=["sorted()", "np.sort()"], n_range=[2**k for k in range(20)], xlabel="len(a)", title="Sort comparison", target_time_per_measurement=1.0, equality_check=None, # outputs differ (list vs ndarray), skip check show_progress=True, ) # Print tabular results to stdout print(out) # Show interactive plot out.show(time_unit="ms") # Save to file with tight layout out.save("sort_comparison.png", transparent=True, bbox_inches="tight") # Save relative-to-first-kernel plot out.save("sort_relative.svg", relative_to=0) ``` -------------------------------- ### `PerfplotData` — Inspecting and re-plotting benchmark results Source: https://context7.com/nschloe/perfplot/llms.txt The object returned by `perfplot.bench()` exposes raw timing data and supports multiple rendering calls, tabular printing, and FLOPS computation. ```APIDOC ## `PerfplotData` — Inspecting and re-plotting benchmark results The object returned by `perfplot.bench()` exposes raw timing data and supports multiple rendering calls, tabular printing, and FLOPS computation. ```python import numpy as np import perfplot out = perfplot.bench( setup=lambda n: np.random.rand(n), kernels=[np.sum, np.mean, np.std], labels=["sum", "mean", "std"], n_range=[2**k for k in range(20)], xlabel="array length", flops=lambda n: n, # each kernel does O(n) FLOPs ) # Inspect raw data print("n_range:", out.n_range) print("timings (s):", out.timings_s) # shape: (n_kernels, len(n_range)) print("labels:", out.labels) # Print formatted table print(out) # Plot absolute runtimes in milliseconds out.show(time_unit="ms", logx=True, logy=True) # Plot relative to np.sum (index 0) out.show(relative_to=0, logy=False) # Save FLOPS plot out.save("flops.svg", transparent=False) ``` ``` -------------------------------- ### perfplot.live() Source: https://context7.com/nschloe/perfplot/llms.txt Renders a matplotlib animation that updates the plot in real time as each n value is measured. Ideal for long-running benchmarks where you want immediate visual feedback. ```APIDOC ## perfplot.live() ### Description Renders a matplotlib animation that updates the plot in real time as each `n` value is measured. Ideal for long-running benchmarks where you want immediate visual feedback. ### Parameters - `setup` (callable) - Function that generates input data for each value in `n_range`. - `kernels` (list of callables) - List of functions to benchmark. - `labels` (list of strings, optional) - Labels for each kernel. - `n_range` (list of ints) - Range of input sizes to benchmark. - `xlabel` (string, optional) - Label for the x-axis. - `target_time_per_measurement` (float, optional) - Target time in seconds for each measurement. - `max_time` (float, optional) - Maximum time in seconds allowed for a single kernel measurement before skipping it. - `equality_check` (callable, optional) - Function to check for equality of results. Defaults to `np.allclose`. - `show_progress` (bool, optional) - Whether to display a progress bar. Defaults to False. - `logx` (string or bool, optional) - Whether to use a log scale for the x-axis. Defaults to 'auto'. - `logy` (string or bool, optional) - Whether to use a log scale for the y-axis. Defaults to 'auto'. ### Request Example ```python import numpy as np import perfplot perfplot.live( setup=lambda n: np.random.rand(n), kernels=[ lambda a: list(a), lambda a: a.tolist(), ], labels=["list()", ".tolist()"], n_range=[2**k for k in range(22)], xlabel="len(a)", target_time_per_measurement=1.0, max_time=5.0, # skip kernel if a single measurement exceeds 5 s equality_check=None, show_progress=True, logx="auto", logy="auto", ) ``` ``` -------------------------------- ### Inspecting and re-plotting benchmark data with PerfplotData Source: https://context7.com/nschloe/perfplot/llms.txt The PerfplotData object returned by perfplot.bench() allows inspection of raw timing data, tabular printing, and multiple plotting calls. Import numpy and perfplot. The 'flops' argument can be used to specify the theoretical FLOP count for FLOPS computation. ```python import numpy as np import perfplot out = perfplot.bench( setup=lambda n: np.random.rand(n), kernels=[np.sum, np.mean, np.std], labels=["sum", "mean", "std"], n_range=[2**k for k in range(20)], xlabel="array length", flops=lambda n: n, # each kernel does O(n) FLOPs ) # Inspect raw data print("n_range:", out.n_range) print("timings (s):", out.timings_s) # shape: (n_kernels, len(n_range)) print("labels:", out.labels) # Print formatted table print(out) # Plot absolute runtimes in milliseconds out.show(time_unit="ms", logx=True, logy=True) # Plot relative to np.sum (index 0) out.show(relative_to=0, logy=False) # Save FLOPS plot out.save("flops.svg", transparent=False) ``` -------------------------------- ### Benchmark and Save Plot to File with perfplot.save() Source: https://context7.com/nschloe/perfplot/llms.txt Use `perfplot.save()` as a convenience wrapper to benchmark kernels and directly save the resulting plot to a file without displaying it. This is useful for automated report generation. Specify the output filename and desired format (e.g., PNG, SVG, PDF). ```python import numpy as np import perfplot perfplot.save( "output/concat_perf.png", # output filename (PNG, SVG, PDF, etc.) transparent=True, setup=np.random.rand, kernels=[ lambda a: np.c_[a, a], lambda a: np.concatenate([a[:, None], a[:, None]], axis=1), ], labels=["c_", "concat"], n_range=[2**k for k in range(20)], xlabel="len(a)", time_unit="us", logx=True, logy=True, ) ``` -------------------------------- ### `perfplot.plot()` — Benchmark and render plot (no display) Source: https://context7.com/nschloe/perfplot/llms.txt Runs `bench()` and calls `plt.plot()`-family functions to draw onto the current matplotlib axes without calling `plt.show()`. Useful when embedding perfplot output into a larger figure. ```APIDOC ## `perfplot.plot()` — Benchmark and render plot (no display) Runs `bench()` and calls `plt.plot()`-family functions to draw onto the current matplotlib axes without calling `plt.show()`. Useful when embedding perfplot output into a larger figure. ```python import matplotlib.pyplot as plt import numpy as np import perfplot fig, axes = plt.subplots(1, 2, figsize=(12, 5)) plt.sca(axes[0]) perfplot.plot( setup=np.random.rand, kernels=[np.sort, lambda a: np.sort(a)[::-1]], labels=["ascending", "descending"], n_range=[2**k for k in range(18)], xlabel="len(a)", title="Sort direction", ) plt.sca(axes[1]) perfplot.plot( setup=np.random.rand, kernels=[np.sum, sum], labels=["np.sum", "sum"], n_range=[2**k for k in range(18)], xlabel="len(a)", title="Sum methods", equality_check=None, ) plt.tight_layout() plt.savefig("combined.png") ``` ``` -------------------------------- ### Separate Benchmarking and Plotting Source: https://github.com/nschloe/perfplot/blob/main/README.md Separates the benchmarking process from the plotting process. This allows for multiple plots from the same benchmark data. The `bench` function returns an object that can be used to show or save the plot. ```python out = perfplot.bench( # same arguments as above (except the plot-related ones, like time_unit or log*) ) out.show() out.save("perf.png", transparent=True, bbox_inches="tight") ``` -------------------------------- ### perfplot.save() Source: https://context7.com/nschloe/perfplot/llms.txt Convenience wrapper that runs bench() and saves the resulting plot directly to a file without displaying it. Useful for scripted report generation. ```APIDOC ## perfplot.save() ### Description Convenience wrapper that runs `bench()` and saves the resulting plot directly to a file without displaying it. Useful for scripted report generation. ### Parameters - `output_filename` (string) - The path to save the plot file (e.g., 'output/plot.png'). Supports various formats like PNG, SVG, PDF. - `setup` (callable) - Function that generates input data for each value in `n_range`. - `kernels` (list of callables) - List of functions to benchmark. - `labels` (list of strings, optional) - Labels for each kernel. - `n_range` (list of ints) - Range of input sizes to benchmark. - `xlabel` (string, optional) - Label for the x-axis. - `time_unit` (string, optional) - Unit for time measurements ('auto', 's', 'ms', 'us', 'ns'). Defaults to 'auto'. - `logx` (bool, optional) - Whether to use a log scale for the x-axis. Defaults to False. - `logy` (bool, optional) - Whether to use a log scale for the y-axis. Defaults to False. - `transparent` (bool, optional) - Whether the saved plot background should be transparent. ### Request Example ```python import numpy as np import perfplot perfplot.save( "output/concat_perf.png", # output filename (PNG, SVG, PDF, etc.) transparent=True, setup=np.random.rand, kernels=[ lambda a: np.c_[a, a], lambda a: np.concatenate([a[:, None], a[:, None]], axis=1), ], labels=["c_", "concat"], n_range=[2**k for k in range(20)], xlabel="len(a)", time_unit="us", logx=True, logy=True, ) ``` ``` -------------------------------- ### Error handling — `PerfplotError` and equality check failures Source: https://context7.com/nschloe/perfplot/llms.txt perfplot raises `PerfplotError` when kernels produce unequal outputs (indicating a bug). Disable checking with `equality_check=None`, or supply a custom comparator. ```APIDOC ## Error handling — `PerfplotError` and equality check failures perfplot raises `PerfplotError` when kernels produce unequal outputs (indicating a bug). Disable checking with `equality_check=None`, or supply a custom comparator. ```python import numpy as np import perfplot from perfplot import PerfplotError def correct_sum(a): return np.sum(a) def buggy_sum(a): return np.sum(a) + 1.0 # intentionally wrong try: perfplot.bench( setup=np.random.rand, kernels=[correct_sum, buggy_sum], labels=["correct", "buggy"], n_range=[2**k for k in range(5)], equality_check=np.allclose, # will catch the discrepancy ) except PerfplotError as e: print(f"Caught PerfplotError: {e}") # → Equality check failure. # correct: ... # buggy: ... ``` ``` -------------------------------- ### Plotting benchmark results with perfplot.plot() Source: https://context7.com/nschloe/perfplot/llms.txt Use perfplot.plot() to run benchmarks and draw plots directly onto matplotlib axes without calling plt.show(). This is useful for embedding perfplot output into larger figures. Ensure matplotlib and numpy are imported. ```python import matplotlib.pyplot as plt import numpy as np import perfplot fig, axes = plt.subplots(1, 2, figsize=(12, 5)) plt.sca(axes[0]) perfplot.plot( setup=np.random.rand, kernels=[np.sort, lambda a: np.sort(a)[::-1]], labels=["ascending", "descending"], n_range=[2**k for k in range(18)], xlabel="len(a)", title="Sort direction", ) plt.sca(axes[1]) perfplot.plot( setup=np.random.rand, kernels=[np.sum, sum], labels=["np.sum", "sum"], n_range=[2**k for k in range(18)], xlabel="len(a)", title="Sum methods", equality_check=None, ) plt.tight_layout() plt.savefig("combined.png") ``` -------------------------------- ### Custom Equality Check in Perfplot Source: https://context7.com/nschloe/perfplot/llms.txt Use a custom equality check for comparing results, such as exact integer equality, when the default floating-point comparison is not suitable. ```python perfplot.show( setup=lambda n: np.random.randint(0, 100, n), kernels=[lambda a: int(np.sum(a)), lambda a: sum(a.tolist())], labels=["np.sum", "sum"], n_range=[2**k for k in range(15)], equality_check=lambda a, b: a == b, # exact integer equality ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.