Skip to content

Instantly share code, notes, and snippets.

@hooopo
Created October 19, 2012 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hooopo/3916850 to your computer and use it in GitHub Desktop.
Save hooopo/3916850 to your computer and use it in GitHub Desktop.
sort.rb
require 'benchmark'
a = (1..100000).map {rand(100000)}
Benchmark.bm(10) do |b|
b.report("Sort") { a.sort }
b.report("Sort by") { a.sort_by {|a| a} }
user system total real
Sort 0.030000 0.000000 0.030000 ( 0.028076)
Sort by 0.140000 0.000000 0.140000 ( 0.138244)
---
require 'benchmark'
a = (1..100000).map {rand(100000)}
Benchmark.bm(10) do |b|
b.report("Sort") { a.sort{|x,y| x <=> y} }
b.report("Sort by") { a.sort_by {|a| a} }
user system total real
Sort 0.250000 0.000000 0.250000 ( 0.251460)
Sort by 0.130000 0.000000 0.130000 ( 0.135658)
---
require 'benchmark'
a = (1..100000).map {rand(100000)}
Benchmark.bm(10) do |b|
b.report("Sort") { a.sort{|x,y| x * a <=> y * a} }
b.report("Sort by") { a.sort_by {|a| a * a} }
user system total real
Sort 1.370000 0.000000 1.370000 ( 1.369499)
Sort by 0.210000 0.000000 0.210000 ( 0.211334)
@jjyr
Copy link

jjyr commented Oct 19, 2012

直接sort快是因为C不用和ruby代码交互的关系吧

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment