Skip to content

Instantly share code, notes, and snippets.

@camallen
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save camallen/29a63c16b03bb9caa255 to your computer and use it in GitHub Desktop.

Select an option

Save camallen/29a63c16b03bb9caa255 to your computer and use it in GitHub Desktop.
Array Intersection vs find / include?
require 'benchmark'
num = 1000000
uss = []
up_to_num = (1..num).to_a
repeat = 100
num_class_subject_ids = 5
Benchmark.bm do |x|
#full set intersection
x.report { repeat.times do |num| ; (up_to_num & [num]).empty? ; end }
#include / find search? for
sim_id_sets = (1..repeat).to_a.map { up_to_num.sample(num_class_subject_ids) }
x.report do
repeat.times do |num|
sim_id_sets[num-1].each do |sid|
up_to_num.include?(sid)
end
end
end
end
# num_class_subject_ids = 2
# user system total real
# 1.340000 0.000000 1.340000 ( 1.334621)
# 0.390000 0.000000 0.390000 ( 0.392117)
# num_class_subject_ids = 5
# user system total real
# 1.070000 0.010000 1.080000 ( 1.085872)
# 0.900000 0.000000 0.900000 ( 0.903072)
#USING find instead of each
Benchmark.bm do |x|
#full set intersection
x.report { repeat.times do |num| ; (up_to_num & [num]).empty? ; end }
#include / find search? for
sim_id_sets = (1..repeat).to_a.map { up_to_num.sample(num_class_subject_ids) }
x.report do
repeat.times do |num|
sim_id_sets[num-1].find do |sid|
up_to_num.include?(sid)
end
end
end
end
#num_class_subject_ids = 2
# user system total real
# 1.110000 0.000000 1.110000 ( 1.108072)
# 0.170000 0.000000 0.170000 ( 0.177406)
#num_class_subject_ids = 5
# user system total real
# 1.110000 0.000000 1.110000 ( 1.111455)
# 0.160000 0.000000 0.160000 ( 0.167238)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment