Last active
January 21, 2020 18:13
-
-
Save burubur/0f679f1ce7727e5b7bd66efc7c47d02e to your computer and use it in GitHub Desktop.
Ruby - List Search Benchmarking (Array, Hash Map, Set)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
require 'benchmark' | |
require 'set' | |
class Bencmarking | |
def prepare | |
write_config | |
end | |
def run | |
puts("bencmarking...\n") | |
id = 940472360 | |
data_in_array = read_config_from_file | |
data_in_hashmap = data_in_array.map { |e| [e, ""] }.to_h | |
data_in_set = data_in_array.to_set | |
Benchmark.bm(0) do |x| | |
x.report { search_from_array(data_in_array, id) } | |
x.report { search_from_hashmap(data_in_hashmap, id) } | |
x.report { search_form_set(data_in_set, id) } | |
end | |
puts("\nbencmarking done.") | |
end | |
def search_from_array(data_in_array, id) | |
puts "\nsearching from %d array:\n" % [data_in_array.length] | |
data_in_array.include?(id) | |
end | |
def search_from_hashmap(data_in_hashmap, id) | |
puts "\nsearching from %d hash map:\n" % [data_in_hashmap.length] | |
data_in_hashmap[id] | |
end | |
def search_form_set(data_in_set, id) | |
puts "\nsearching from %d set:\n" % [data_in_set.length] | |
data_in_set.include?(id) | |
end | |
def read_config_from_file | |
file_name = "./sample_1000000.json" | |
file = File.open(file_name).read | |
driver_ids = Kernel.eval(file).to_a | |
driver_ids | |
end | |
def write_config | |
require 'json' | |
id = 940417010 | |
temp_data = [] | |
1000000.times do | |
id = id + 1 | |
temp_data.push(id) | |
end | |
File.open("sample_1000000.json", "w") do |f| | |
f.write(temp_data.to_json) | |
end | |
end | |
end | |
bm = Bencmarking.new | |
#bm.prepare # uncomment this line to generate the sample file | |
bm.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment