Ruby中的基准测试方法

用户名

我正在尝试对这样的一组计算进行基准测试-

def benchmark(func, index, array)
    start = Time.now
    func(index, array)
    start - Time.now #returns time taken to perform func
end

def func1(index, array)
    #perform computations based on index and array
end 

def func2(index, array)
    #more computations....
end

benchmark(func1, index1, array1)
benchmark(func1, index2, array2)

现在我想知道如何实现这一目标。我试过这个例子,但是吐出来了

`func1': wrong number of arguments (0 for 2) (ArgumentError)

如果我尝试-

benchmark(func1(index1, array1), index1, array1)

它吐出来...

undefined method `func' for main:Object (NoMethodError)

我看到了一个类似的问题,但这是针对python的。将带有参数的函数传递给Python中的另一个函数?有人可以协助吗?谢谢。

阿杰迪32

在Ruby中,可以在方法名称后不包含空括号的情况下调用方法,如下所示:

def func1
  puts "Hello!"
end

func1 # Calls func1 and prints "Hello!"

因此,在编写时benchmark(func1, index1, array1),实际上是func1在不带参数的情况下进行调用,并将结果传递给benchmark,而不是func1按预期传递给基准函数。为了func1作为对象传递,您可以使用method方法获得该函数的包装对象,如下所示:

def func1
  puts "Hello!"
end

m = method(:func1) # Returns a Method object for func1
m.call(param1, param2)

但是,大多数时候,这并不是您真正想要做的。Ruby支持一种称为块的构造,该构造更适合于此目的。您可能已经熟悉了eachRuby用于遍历数组迭代器中的这是在您的用例中使用块的外观:

def benchmark
  start = Time.now
  yield
  Time.now - start # Returns time taken to perform func
end

# Or alternately:
# def benchmark(&block)
#   start = Time.now
#   block.call
#   Time.now - start # Returns time taken to perform func
# end

def func1(index, array)
    # Perform computations based on index and array
end 

def func2(index, array)
    # More computations....
end

benchmark { func1(index1, array1) }
benchmark { func1(index1, array2) }

实际上,Ruby有一个称为Benchmark的标准基准测试库,该库使用块,并且可能已经完全满足您的要求。

用法:

require 'benchmark'

n = 5000000
Benchmark.bm do |x|
  x.report { for i in 1..n; a = "1"; end }
  x.report { n.times do   ; a = "1"; end }
  x.report { 1.upto(n) do ; a = "1"; end }
end

结果:

    user     system      total        real
1.010000   0.000000   1.010000 (  1.014479)
1.000000   0.000000   1.000000 (  0.998261)
0.980000   0.000000   0.980000 (  0.981335)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在python中对运行时间进行基准测试

来自分类Dev

如何在JMH基准测试中生成方法?

来自分类Dev

Memcached的UDP基准测试

来自分类Dev

卡尺基准测试中的非确定性分配行为

来自分类Dev

MATLAB性能基准测试

来自分类Dev

在Webdriver中对Firefox和Chrome的内存消耗进行基准测试

来自分类Dev

Redis集群基准测试

来自分类Dev

如何在Elasticsearch中对执行进行基准测试?

来自分类Dev

Maven工件基准测试

来自分类Dev

访问基准测试结果

来自分类Dev

在Go中绘制基准测试结果

来自分类Dev

Prolog中微基准测试的维度

来自分类Dev

防止在Criterion基准测试中缓存计算

来自分类Dev

如何在Crypto ++库基准测试中运行?

来自分类Dev

多线程环境中的基准测试

来自分类Dev

在这个基准测试中,Node的速度有多快?

来自分类Dev

基准测试结果奇怪

来自分类Dev

BaseX中的基准测试:如何设置

来自分类Dev

FreeBSD中的MySQLSlap基准测试

来自分类Dev

在Julia中对数组的条件赋值进行基准测试

来自分类Dev

推荐的用于对Ruby和Perl进行基准测试的工具

来自分类Dev

MySQL基准测试

来自分类Dev

如何在Elasticsearch中对执行进行基准测试?

来自分类Dev

Ubuntu资源基准测试

来自分类Dev

Ruby on Rails的方法基准性能

来自分类Dev

我可以在Ruby测试中伪造调用方法吗?

来自分类Dev

Netlogo 基准测试

来自分类Dev

riscv 基准测试中与 vvadd 和 mt-vvadd 的区别

来自分类Dev

如何使用文件中的数据进行微基准测试?