我正在尝试对这样的一组计算进行基准测试-
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中的另一个函数?有人可以协助吗?谢谢。
在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支持一种称为块的构造,该构造更适合于此目的。您可能已经熟悉了each
Ruby用于遍历数组的迭代器中的块。这是在您的用例中使用块的外观:
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] 删除。
我来说两句