How about (size-1).downto(0) {|i| ... } ?
Too Slow. Firstly, all those calls to Integer#- are a killer, but downto
just isn't as efficient as each. Probably because downto calls Integer#-
internally to get the next index, whereas having the array of all
integers already in memory speeds things along.
require 'benchmark'
Benchmark.bm(18) do |bm|
size = 10
s = (0...size).to_a.reverse
sminus = size - 1
bm.report("range") { 1_000_000.times {s.each {}} }
bm.report("downto") { 1_000_000.times {(size-1).downto(0) {}} }
bm.report("downto2") { 1_000_000.times {(sminus).downto(0) {}} }
end
user system total real
range 2.188000 0.000000 2.188000 ( 2.188000)
downto 2.641000 0.000000 2.641000 ( 2.656000)
downto2 2.437000 0.000000 2.437000 ( 2.469000)
And since in this case, you're going to be running it a few million
times, it does make a difference.
If I wanted to do irrelevant squeezing, I should have used
'Array.new(size) {|i| i}.reverse' to construct the s array instead of
the range, but loosing a few fractions of a millisecond during the setup
is not really a worry - unless it's happening within the while loop,
it's irrelevant.
I think I've squeezed that permutation function every which way that it
can be squeezed that makes an ounce of difference..
···
-----Original Message-----
From: Sean O'Halpin [mailto:sean.ohalpin@gmail.com]
Sent: Monday, 7 November 2005 12:25 PM
To: ruby-talk ML
Subject: Re: Fun with Permutations (including new change for Facets)On 11/7/05, Daniel Sheppard <daniels@pronto.com.au> wrote:
> The saving however, is in the order of nanosecondsEvery little helps!
> I would have preferred if ((size-1)..0).each actually iterated, but
> them's the breaks.Regards,
Sean
#####################################################################################
This email has been scanned by MailMarshal, an email content filter.
#####################################################################################