我在使用rspec測試時遇到了問題。我正在使用Ruby 1.93和RSPEC 2.14.8(我認爲)對不起,這篇文章將會持續多久。我可以得到我發現的其他代碼,但無法讓我的代碼正常工作,但我不知道爲什麼。麻煩通過RSpec測試。時間不能強制轉換爲Fixnum
我的代碼:
def measure(number = 1)
counter = number
total = 0
while counter > 0
start = Time.now
counter-=1
yield
stop = Time.now
total = total + stop - start
end
total/number
end
其他的代碼,我發現,工作原理:
def measure count=1
total_time = 0
count.times do
start_time = Time.now
yield
end_time = Time.now
total_time += end_time - start_time
end
total_time/count
end
測試:
require_relative "performance_monitor"
require "time" # loads up the Time.parse method -- do NOT create time.rb!
describe "Performance Monitor" do
before do
@eleven_am = Time.parse("2011-1-2 11:00:00")
end
it "takes about 0 seconds to run an empty block" do
elapsed_time = measure do
end
elapsed_time.should be_within(0.1).of(0)
end
it "takes exactly 0 seconds to run an empty block (with stubs)" do
Time.stub(:now) { @eleven_am }
elapsed_time = measure do
end
elapsed_time.should == 0
end
it "takes about 1 second to run a block that sleeps for 1 second" do
elapsed_time = measure do
sleep 1
end
elapsed_time.should be_within(0.1).of(1)
end
it "takes exactly 1 second to run a block that sleeps for 1 second (with stubs)" do
fake_time = @eleven_am
Time.stub(:now) { fake_time }
elapsed_time = measure do
fake_time += 60 # adds one minute to fake_time
end
elapsed_time.should == 60
end
it "runs a block N times" do
n = 0
measure(4) do
n += 1
end
n.should == 4
end
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
it "returns the average time when running a random number of times for random lengths of time" do
fake_time = @eleven_am
Time.stub(:now) { fake_time }
number_of_times = rand(10) + 2
average_time = measure(number_of_times) do
delay = rand(10)
fake_time += delay
end
average_time.should == (fake_time - @eleven_am).to_f/number_of_times
end
end
什麼它說當我運行它:
Performance Monitor takes about 0 seconds to run an empty block (FAILED - 1)
Failures:
1) Performance Monitor takes about 0 seconds to run an empty block
Failure/Error: elapsed_time = measure do
TypeError:
Time can't be coerced into Fixnum
# ./06_performance_monitor/performance_monitor.rb:11:in '+' #./06_performance_monitor/performance_monitor.rb:11:in 'measure' #./06_performance_monitor/performance_monitor_spec.rb:21:in `block (2 levels) in 'Finished in 0.008 seconds 1 example, 1 failure
謝謝。我會爲你的答案投票,但我的聲望很低。 – tmfahall
在第一次循環之後,總共=總數+(停止 - 開始)是否仍然一起增加兩次? – tmfahall
'停止 - 開始'將返回一個浮點數(兩次之間的秒數)而不是時間。你可以添加一個浮點到一個時間。嘗試在irb中使用這個來了解發生了什麼。它通常幫助我弄清楚Ruby如何工作。 – benjaminjosephw