Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 15th, 2012  |  syntax: None  |  size: 0.52 KB  |  hits: 7  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. def recur_length list
  2.   return 0 if list.empty?
  3.   1 + recur_length(list.drop 1 )
  4. end
  5.  
  6. nums = (1..1000).to_a
  7.  
  8. start = Time.now
  9. recur_length nums
  10. fin = Time.now
  11.  
  12. puts "list size of 1000..."
  13. puts "recursive: #{fin - start} seconds"
  14.  
  15. def iter_length list
  16.   size = 0
  17.   list.each {|i| size += 1}
  18.   size
  19. end
  20.  
  21. nums = (1..1000).to_a
  22.  
  23. start = Time.now
  24. iter_length nums
  25. fin = Time.now
  26.  
  27. puts "non-recursive: #{fin - start} seconds"
  28.  
  29.  
  30. ###### output #######
  31. # list size of 1000...
  32. # recursive: 0.000437 seconds
  33. # non-recursive: 0.000128 seconds