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
  20. base2 = n.to_s(2)
  21. base10 == base10.reverse && base2 == base2.reverse
  22. end.reduce(0, :+)
  23. end
  24.  
  25. def profile_optimization
  26. result = without_optimization
  27. duration = time_it do
  28. ITERATIONS.times { without_optimization }
  29. end
  30. puts "Without optimization took #{duration/ITERATIONS}s per iteration to return #{result}"
  31.  
  32. result = with_optimization
  33. duration = time_it do
  34. ITERATIONS.times { with_optimization }
  35. end
  36. puts "With optimization took #{duration/ITERATIONS}s per iteration to return #{result}"
  37.  
  38. end
  39. end
  40. end
  41.  
  42. PerformanceCheck.profile_optimization
Success #stdin #stdout 7.05s 4760KB
stdin
Standard input is empty
stdout
Without optimization took 0.957107193s per iteration to return 872187
With optimization took 1.388751984s per iteration to return 872187