Skip to content

Instantly share code, notes, and snippets.

@maxjustus
Last active September 10, 2015 22:04
Show Gist options
  • Save maxjustus/f9e8993754bb50bc6d6d to your computer and use it in GitHub Desktop.
Save maxjustus/f9e8993754bb50bc6d6d to your computer and use it in GitHub Desktop.
Quickly finding count of common elements in same length arrays in Ruby using RubyInline
Calculating -------------------------------------
ruby version 369 i/100ms
c version 3413 i/100ms
-------------------------------------------------
ruby version 3977.2 (±4.5%) i/s - 19926 in 5.020612s
c version 450675.5 (±9.4%) i/s - 2221863 in 4.986029s
~/dev/theclymb$ ./bin/rails runner bench.rb
Calculating -------------------------------------
ruby version 360 i/100ms
c version 3385 i/100ms
-------------------------------------------------
ruby version 3923.5 (±4.9%) i/s - 19800 in 5.059191s
c version 446588.8 (±9.7%) i/s - 2193480 in 4.968438s
require 'benchmark/ips'
require 'inline'
class Example
inline do |builder|
builder.c "
static VALUE common_element_count(VALUE a1, VALUE a2) {
int a_len = RARRAY_LEN(a1);
int count = 0;
int i = 0;
VALUE *a1_arr = RARRAY_PTR(a1);
VALUE *a2_arr = RARRAY_PTR(a2);
for(i = 0; i < a_len; i++) {
if (a1_arr[i] == a2_arr[i]) {
count++;
}
}
return INT2NUM(count);
}"
end
def common_element_count_rb(a1, a2)
count = 0
i = 0
len = a1.length
while i < len
count += 1 if a1[i] == a2[i]
i += 1
end
count
end
end
source_a = 10000.times.to_a
a1 = source_a.sample(5000)
a2 = source_a.sample(5000)
ex = Example.new
Benchmark.ips do |x|
x.report('ruby version') do
ex.common_element_count_rb(a1, a2)
end
x.report('c version') do
ex.common_element_count(a1, a2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment