2

我是一个新手,试图在本教程中解决一些问题:http: //testfirst.org/live/learn_ruby/performance_monitor

我当前的代码通过了 7 个中的 5 个,最后两个失败了。我认为问题在于我真的不明白它的要求:

it "returns the average time, not the total time, when running multiple times" do
  run_times = [8,6,5,7]
  fake_time = @eleven_am
  Time.stub(:now) { fake_time }
  average_time = measure(4) do
    fake_time += run_times.pop
  end
  average_time.should == 6.5
end

这是我目前拥有的:

def measure(x=0)

  if x>0
    x.times do yield end
  else
    y= Time.now
    yield 
    elapsed_time=Time.now-y
    elapsed_time
  end
end

我不是在寻找复制和粘贴的答案。我想清楚它的要求,以及我如何应对挑战。谢谢。

4

1 回答 1

0

The spec is expecting that the performance monitor doesn't return the total of the times, but average. Your current version of the code is returning neither the total, nor the average, but the count of the times the yield statement was called.

Your current version of the solution is failing with the following error:

1) Performance Monitor returns the average time, not the total time, when running multiple times
   Failure/Error: average_time.should == 6.5
     expected: 6.5
          got: 4 (using ==)
   # ./06_performance_monitor/performance_monitor_spec.rb:64

So you are returning the count and not the average of [8,6,5,7].

If the spec fails with the following error, it is returning the sum ( 26.0 = 8 + 6+ 5 + 7 ):

1) Performance Monitor returns the average time, not the total time, when running multiple times
   Failure/Error: average_time.should == 6.5
     expected: 6.5
          got: 26.0 (using ==)
   # ./06_performance_monitor/performance_monitor_spec.rb:64

Couple of pointers to help you move forward:

  1. Look at your assumption that the count should default to 0 (as defined by x=0 param being passed to measure. If the program calls measure without any parameters, wouldn't it make sense to say it has been called once rather than zero times?

  2. Try to understand why your program is returning 4 by walking through the code for measure on each value of [8,6,5,7], and by modifying/adding new test cases in performance_monitor_spec.rb file. Hint: The code isn't doing any performance monitoring in this path ;-)

于 2013-02-12T00:09:49.197 回答