Skip to content

Instantly share code, notes, and snippets.

@kei-s
Last active September 19, 2017 02:00
Show Gist options
  • Save kei-s/b303aca105df5c26be9c98f833db80f7 to your computer and use it in GitHub Desktop.
Save kei-s/b303aca105df5c26be9c98f833db80f7 to your computer and use it in GitHub Desktop.
Comparable#clamp improvement
require 'benchmark'
Benchmark.bmbm do |x|
v = Random.rand(-10..110)
x.report "minmax:" do
10000000.times { [99, [0, v].max].min }
end
x.report "clamp: " do
10000000.times { v.clamp(0, 99) }
end
end
diff --git a/compar.c b/compar.c
index 02529c9960..5cfcccf36e 100644
--- a/compar.c
+++ b/compar.c
@@ -9,9 +9,12 @@
**********************************************************************/
+#include "internal.h"
#include "ruby/ruby.h"
#include "id.h"
+#define id_cmp idCmp
+
VALUE rb_mComparable;
static VALUE
@@ -87,7 +90,8 @@ cmp_equal(VALUE x, VALUE y)
static int
cmpint(VALUE x, VALUE y)
{
- return rb_cmpint(rb_cmp(x, y), x, y);
+ struct cmp_opt_data cmp_opt = { 0, 0 };
+ return OPTIMIZED_CMP(x, y, cmp_opt);
}
/*
# ruby -v
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
# ruby /src/github.com/kei-s/sketch/ruby/clamp_bench.rb
Rehearsal -------------------------------------------
minmax: 0.870000 0.000000 0.870000 ( 0.872666)
clamp: 1.920000 0.000000 1.920000 ( 1.924521)
---------------------------------- total: 2.790000sec
user system total real
minmax: 0.740000 0.000000 0.740000 ( 0.732744)
clamp: 2.060000 0.010000 2.070000 ( 2.072794)
# /usr/local/bin/ruby -v
ruby 2.5.0dev (2017-09-13 trunk 59863) [x86_64-linux]
# /usr/local/bin/ruby /src/github.com/kei-s/sketch/ruby/clamp_bench.rb
Rehearsal -------------------------------------------
minmax: 0.890000 0.010000 0.900000 ( 0.900237)
clamp: 1.120000 0.000000 1.120000 ( 1.120490)
---------------------------------- total: 2.020000sec
user system total real
minmax: 0.820000 0.000000 0.820000 ( 0.822517)
clamp: 1.090000 0.000000 1.090000 ( 1.087491)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment