Guest User

testfirstorg_ruby_06

a guest
Jun 23rd, 2014
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.00 KB | None | 0 0
  1. # # Topics
  2. #
  3. # * stubs
  4. # * blocks
  5. # * yield
  6. #
  7. # # Performance Monitor
  8. #
  9. # This is (a stripped down version of) an actual useful concept: a function that runs a block of code and then tells you how long it took to run.
  10.  
  11. require "performance_monitor"
  12.  
  13. require "time"  # loads up the Time.parse method -- do NOT create time.rb!
  14.  
  15. describe "Performance Monitor" do
  16.   before do
  17.     @eleven_am = Time.parse("2011-1-2 11:00:00")
  18.   end
  19.  
  20.   it "takes about 0 seconds to run an empty block" do
  21.     elapsed_time = measure do
  22.     end
  23.     elapsed_time.should be_within(0.1).of(0)
  24.   end
  25.  
  26.   it "takes exactly 0 seconds to run an empty block (with stubs)" do
  27.     Time.stub(:now) { @eleven_am }
  28.     elapsed_time = measure do
  29.     end
  30.     elapsed_time.should == 0
  31.   end
  32.  
  33.   it "takes about 1 second to run a block that sleeps for 1 second" do
  34.     elapsed_time = measure do
  35.       sleep 1
  36.     end
  37.     elapsed_time.should be_within(0.1).of(1)
  38.   end
  39.  
  40.   it "takes exactly 1 second to run a block that sleeps for 1 second (with stubs)" do
  41.     fake_time = @eleven_am
  42.     Time.stub(:now) { fake_time }
  43.     elapsed_time = measure do
  44.       fake_time += 60  # adds one minute to fake_time
  45.     end
  46.     elapsed_time.should == 60
  47.   end
  48.  
  49.   it "runs a block N times" do
  50.     n = 0
  51.     measure(4) do
  52.       n += 1
  53.     end
  54.     n.should == 4
  55.   end
  56.  
  57.   it "returns the average time, not the total time, when running multiple times" do
  58.     run_times = [8,6,5,7]
  59.     fake_time = @eleven_am
  60.     Time.stub(:now) { fake_time }
  61.     average_time = measure(4) do
  62.       fake_time += run_times.pop
  63.     end
  64.     average_time.should == 6.5
  65.   end
  66.  
  67.   it "returns the average time when running a random number of times for random lengths of time" do
  68.     fake_time = @eleven_am
  69.     Time.stub(:now) { fake_time }
  70.     number_of_times = rand(10) + 2
  71.     average_time = measure(number_of_times) do
  72.       delay = rand(10)
  73.       fake_time += delay
  74.     end
  75.     average_time.should == (fake_time - @eleven_am).to_f/number_of_times
  76.   end
  77.  
  78. end
Advertisement
Add Comment
Please, Sign In to add comment