我有一个 gem 可以进行一些艰难的数字运算:它从图像中裁剪出“有趣”的部分。为此,我设置了几种算法。总的来说,它只是表现不佳;显然,我想改进这一点:)。
我想测试和测量三件事:
- 内存使用情况
- CPU 使用率
- 在方法/例程中花费的总时间。
我想对此进行调查并比较各种算法、参数和设置的值。
是否有一些 Ruby 功能、gem 或类似的东西,可以让我运行我的代码,更改一些参数或一点代码,再次运行它,然后比较结果?
顺便说一下,我已经有了 test:unit 和 Shoulda,所以如果有东西使用这些测试框架,那就没问题了。
最佳答案
您可以使用标准的“分析器”库。它报告每种方法所花费的时间。
require 'profiler'
def functionToBeProfiled
a = 0
1000.times do |i|
a = a + i * rand
end
end
Profiler__::start_profile
functionToBeProfiled
Profiler__::stop_profile
Profiler__::print_profile($stdout)
这将产生以下输出:
% cumulative self self total
time seconds seconds calls ms/call ms/call name
16.58 0.03 0.03 1 31.00 93.00 Integer#times
16.58 0.06 0.03 1000 0.03 0.03 Kernel.rand
8.56 0.08 0.02 3 5.33 10.33 RubyLex#identify_identifier
8.56 0.09 0.02 10 1.60 6.20 IRB::SLex::Node#match_io
8.56 0.11 0.02 84 0.19 0.19 Kernel.===
8.56 0.13 0.02 999 0.02 0.02 Float#+
8.56 0.14 0.02 6 2.67 5.33 String#gsub!
但是要小心,因为这个库会影响您的应用程序的性能。仅当与使用相同方法获得的其他测量值进行比较时,您从中获得的测量值才有用。它们不能用于评估绝对测量值。
关于ruby - 独立 Ruby 代码 (gem) 的性能和资源测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5678553/