如何多次运行一段测试代码?

时间:2013-01-24 13:29:39

标签: ruby loops yield block

我正在构建Test-First-Teaching performance_monitor并且可以进行第五次测试但是它失败了。

为什么我的块只运行一次?

这是我的代码:

require "time"
t = Time.now
def measure x=0
start = Time.now
    yield x 
endt = Time.now - start
    end
measure(4){ |x| x.times do Time.now - t end}

这是错误:

*Error____
Performance Monitor
  takes about 0 seconds to run an empty block
  takes exactly 0 seconds to run an empty block (with stubs)
  takes about 1 second to run a block that sleeps for 1 second
  takes exactly 1 second to run a block that sleeps for 1 second (with stubs)
  runs a block N times (FAILED - 1)

Failures:

  1) Performance Monitor runs a block N times
     Failure/Error: n.should == 4
       expected: 4
            got: 1 (using ==)

2 个答案:

答案 0 :(得分:1)

这样想:您的measure方法是负责确保传递给它的块运行正确次数的方法。因此,传递给measure的块应该只包含应该在单个迭代中运行的代码。

对于一个简单的例子(主题从加里伯恩哈特的"WAT"谈话中无耻地撕掉):

def repeat_x_times(x)
    # This runs the passed block x times:
    x.times do
        yield
    end
end

repeat_x_times(16) do
    # This is what should happen in a single iteration:
    puts 0.0 / 0.0
end

puts 'Batman!'

关于块的另一个好处是你可以随时访问与块相同范围内的变量(通常是局部变量),无论产量在何处发生:

i = 3
4.times {i += 1} # We can still get to i!
puts i           # Prints "7"

将这两个概念合并为一个稍微复杂的例子:

array = [3, 6, 9, 12, 15]
sum = 0
array.each do |item|
    # In the first iteration, item is 3; in the second it's 6, and so on:
    sum += item
end
puts sum

现在,我知道我没有直接回答你的问题,但听起来你正在学习Ruby,所以希望这比切割粘贴更有用......无论如何,只要玩这个直到你明白了,很快你就会希望所有的语言都有这么有用的功能!

答案 1 :(得分:0)

我想出了什么:

    require "time"

    def measure (x=1)
        elapsed = 0
        x.times do
        start = Time.now
        yield
        endt = Time.now
        elapsed += endt - start
   end
   elapsed / x
   if elapsed < 1 
        time = "milliseconds"
   else
        time = "seconds"

    end
    puts "We ran this block #{x} times \nand it took #{elapsed} #{time}"
    end

    measure(50000){puts "Run a block" }