fork download
  1. module PerformanceCheck
  2. class << self
  3. ITERATIONS = 2
  4.  
  5. def time_it
  6. start_time = Time.now
  7. yield
  8. Time.now - start_time
  9. end
  10.  
  11. def without_optimization
  12. (1...1_000_000).select do |n|
  13. n.to_s == n.to_s.reverse && n.to_s(2) == n.to_s(2).reverse
  14. end.reduce(0, :+)
  15. end
  16.  
  17. def with_optimization
  18. (1...1_000_000).select do |n|
  19. (base10 = n.to_s) == base10.reverse && (base2 = n.to_s(2)) == base2.reverse
  20. end.reduce(0, :+)
  21. end
  22.  
  23. def profile_optimization
  24. result = without_optimization
  25. duration = time_it do
  26. ITERATIONS.times { without_optimization }
  27. end
  28. puts "Without optimization took #{duration/ITERATIONS}s per iteration to return #{result}"
  29.  
  30. result = with_optimization
  31. duration = time_it do
  32. ITERATIONS.times { with_optimization }
  33. end
  34. puts "With optimization took #{duration/ITERATIONS}s per iteration to return #{result}"
  35.  
  36. end
  37. end
  38. end
  39.  
  40. PerformanceCheck.profile_optimization
Success #stdin #stdout 5.06s 4760KB
stdin
Standard input is empty
stdout
Without optimization took 0.963699818s per iteration to return 872187
With optimization took 0.7273705415s per iteration to return 872187