跳转到主要内容

Richbench,一个小型基准测试工具

项目描述

rich-bench

一个小型的Python基准测试工具。

我为什么需要这个?

Python内置的timeit模块很棒,但典型的小型基准测试用法是运行一个像这样的小脚本:

python -m timeit "a = 1; b = 2; a * b"

这种方法的缺点是编译后的代码是一个模块,因此顶层上的任何变量都是全局变量。编译后的字节码与在局部作用域(例如方法或函数)中执行相同的语句不同。在CPython中,它们的行为和性能差异很大。

richbench鼓励你在函数内编写基准测试,以正确模拟生产代码的闭包和作用域。

安装

需要Python 3.6+,可以使用pip进行安装

pip安装richbench

使用方法

在目录中编写基准测试函数,并使用该目标运行richbench以获取结果

$ richbench my_benchmarks/

结果以如下表格形式显示

Example result table

$ richbench --help
usage: richbench [-h] [--profile] [--percentage] [--markdown] [--benchmark [BENCHMARK]] [--repeat REPEAT] [--times TIMES] target [target ...]

positional arguments:
  target

options:
  -h, --help            show this help message and exit
  --profile             Profile the benchmarks and store in .profiles/
  --percentage          Show percentage of improvement instead of multiplier
  --markdown            Prints a markdown friendly table
  --benchmark [BENCHMARK]
                        Run specific benchmark
  --repeat REPEAT       Repeat benchmark this many times
  --times TIMES         Run benchmark this many times

编写基准测试

基准测试应该在目录中,并且必须具有bench_{name}.py的文件名。

基准测试文件中的最后一行应该是名为__benchmarks__的列表,其中包含包含以下内容的元组列表:

  1. 函数a
  2. 函数b
  3. 基准测试的名称
def sort_seven():
    """Sort a list of seven items"""
    for _ in range(10_000):
        sorted([3,2,4,5,1,5,3])

def sort_three():
    """Sort a list of three items"""
    for _ in range(10_000):
        sorted([3,2,4])

__benchmarks__ = [
    (sort_seven, sort_three, "Sorting 3 items instead of 7")
]

基准测试提示

在您的基准测试函数内部尝试以下操作:

  • 一次性运行设置命令
  • 尽可能多地重复您要基准测试的代码以创建一个稳定的基准测试

对于微型基准测试,这可以通过调用1000 - 100,000次来实现。

如果您的基准测试代码在0.001s内完成,则很可能会因为CPU执行其他活动而导致基准测试不稳定。增加函数内目标代码运行的次数。

性能分析

通过在命令行中添加--profile标志,它将生成一个子目录.profiles,其中包含目标函数的HTML配置文件。

项目详情


下载文件

下载适合您平台文件的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源代码分发

richbench-1.0.3.tar.gz (1.1 MB 查看哈希值)

上传时间 源代码

构建分发

richbench-1.0.3-py3-none-any.whl (5.2 kB 查看哈希值)

上传时间 Python 3