From: Fred Phillips Date: 2008-08-25T03:06:48+09:00 Subject: Re: Array.shuffle/Array.shuffle! --6c2NcOVqGQ03X4Wi Content-Type: text/plain; charset=utf-8 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sun Aug 24 19:17:11 2008, Stefan Rusterholz wrote: > which for many cases probably still is faster in ruby since it runs > mainly in C, I didn't bench it, though Seems you=E2=80=99re right: Rehearsal ------------------------------------------------------- Knuth: 10.900000 0.000000 10.900000 ( 10.902161) Sort by #{rand}: 11.050000 0.000000 11.050000 ( 11.060635) --------------------------------------------- total: 21.950000sec user system total real Knuth: 10.930000 0.020000 10.950000 ( 10.946718) Sort by #{rand}: 11.020000 0.000000 11.020000 ( 11.020902) require 'benchmark' class Array # Shuffle the array = =20 def shuffle! n =3D length for i in 0...n r =3D Kernel.rand(n-i)+i self[r], self[i] =3D self[i], self[r] end self end # Return a shuffled copy of the array = =20 def shuffle dup.shuffle! end end =20 n =3D 500=20 =20 a =3D (1..10000).map { rand } Benchmark.bmbm(20) do |x| x.report("Knuth:") { n.times { a.shuffle } } x.report('Sort by #{rand}:') { n.times { a.sort_by { rand } } } end --=20 Fred O. Phillips http://fophillips.org BBC7 7572 755F 83E0 3209 504A E4F7 874F 1545 9D41 --6c2NcOVqGQ03X4Wi Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.9 (GNU/Linux) iEYEARECAAYFAkixpC0ACgkQ5PeHTxVFnUGJSwCgxdCHQ+oY8KiCX+mJhTpt1KHb DLcAoIe17TOkbksd3275RgPlZG1G2VXh =MjmL -----END PGP SIGNATURE----- --6c2NcOVqGQ03X4Wi--