快捷搜索:  汽车  科技

ruby原理剖析,基准测试初学者指南

ruby原理剖析,基准测试初学者指南所以我们的代码总共运行了大约 1.05 秒。时间单位是秒。Benchmark.bm do |bench| bench.report('Performance Test 1') do # execute some code here end bench.report('Performance Test 2') do # execute some other code here end end对于本教程,我们将只测试一个代码块:Benchmark.bm do |bench| bench.report('Testing some code') do # execute some code here end end这将为我们提供类似于以下内容的输出:user system total

这是一个快速的分步指南,适用于您需要即时进行一些性能测试。

Ruby 有一个内置的基准测试模块,该模块易于使用且足够有效,足以涵盖您的标准用例。 使用几个函数之一,我们可以快速隔离代码的非执行部分。

ruby原理剖析,基准测试初学者指南(1)

基准报告

Benchmark.bm 方法为我们传递给它的任何代码块提供性能指标的打印输出。 我们可以把它分成多个代码块来执行,一次测试不同的东西。 我们将收到多份报告,每次使用报告方法一份。

Benchmark.bm do |bench| bench.report('Performance Test 1') do # execute some code here end bench.report('Performance Test 2') do # execute some other code here end end

对于本教程,我们将只测试一个代码块:

Benchmark.bm do |bench| bench.report('Testing some code') do # execute some code here end end

这将为我们提供类似于以下内容的输出:

user system total real 0.544000 0.036000 0.580000 (1.049005)

每个报告都显示用户 CPU 时间、系统 CPU 时间、总和 CPU 时间和经过的实时时间。

时间单位是秒。

所以我们的代码总共运行了大约 1.05 秒。

让我们更进一步,更彻底地分析我们的代码。

代码分析

我们希望准确了解我们的代码在小样本数据上运行需要多长时间。 然后我们将评估代码在更大的数据池中的执行情况。

Benchmark.bm do |bench| bench.report('Testing some code') do process_100_records end end

让我们运行这个基准测试 5 次并记录结果。

user system total real Run 1: 0.544000 0.036000 0.580000 (1.049005) Run 2: 0.500000 0.080000 0.580000 (1.059239) Run 3: 0.520000 0.048000 0.568000 (1.026662) Run 4: 0.536000 0.048000 0.584000 (1.066434) Run 5: 0.496000 0.080000 0.576000 (1.050087)

我们将平均结果。 您可能希望丢弃您收到的最小和最大运行时间,尤其是当它们明显偏离平均值时。

对于本教程,我们将保留所有 5 个结果。

这是一个快速脚本,用于确定更大数据池的预期运行时间。 对于此示例,我们有 100 条记录的样本大小和 1M 条记录的完整数据大小。

# This code can be run in a terminal - just edit the variablesdef avg(array) array.sum(0.0) / array.size end def seconds_to_hms(sec) "d:d:d" % [sec / 3600 sec / 60 % 60 sec % 60] end # Fill in these variables with your own results realtimes = [1.049005 1.059239 1.026662 1.066434 1.050087] sample_size = 100 full_data_size = 1000000average_time = avg(realtimes)# predicted runtime for full data size expected_runtime = average_time / sample_size * full_data_size p seconds_to_hms expected_runtime => "02:55:02"

此代码将需要大约 3 个小时才能运行(!)

这是否可以接受将取决于您的用例,但现在您拥有做出决定所需的信息。

我希望这有帮助。 祝你在球场上好运!

猜您喜欢: