Created
September 14, 2016 22:53
-
-
Save davingee/f274e380076e2aa8442f7328eb1673b4 to your computer and use it in GitHub Desktop.
benchmark
This file contains 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 'pry' | |
require 'benchmark' | |
require 'benchmark-memory' | |
class User | |
def initialize( args = {} ) | |
raise 'user_ids needs to be an array' unless args[:user_ids].is_a?(Array) | |
@user_ids = args[:user_ids] | |
end | |
def top_user_ids_0(k) | |
results = Hash.new{ |k, v| k[ v ] = 0 } | |
@user_ids.each { |id| results[ id ] += 1 } | |
results.sort_by{ |k, v| v <=> v}[0, k].map{ |u| u[0]} | |
end | |
def top_user_ids_3(k) | |
results = Hash.new{ |k, v| k[ v ] = 0 } | |
@user_ids.each { |id| | |
results[ id ] += 1 | |
}.sort_by{ |k, v| | |
v <=> v | |
}[0, k].map{ |u| | |
u[0] | |
} | |
end | |
def top_user_ids_1(k) | |
@user_ids.group_by{ | |
|k| k | |
}.sort_by{ |k, v| | |
v.count <=> v.count | |
}.first( k ).map{ |d| d[0] } | |
end | |
def top_user_ids_2(k) | |
@user_ids.each_with_object( Hash.new( 0 ) ){ |user_id, counts| | |
counts[user_id] += 1 | |
}.sort_by{ |k, v| | |
v <=> v | |
}[0, k].map{ |u| | |
u[0] | |
} | |
end | |
def self.test_a_method(n) | |
k = 4 | |
array = [1,1, 3, 4, 6, 7,3, 1, 6, 8, 8, 8, 8, 8, 2, 1 ] | |
u = User.new( user_ids: array ) | |
u.send("top_user_ids_#{ n }", k ) | |
end | |
def self.benchmark | |
array = [1,1, 3, 4, 6, 7,3, 1, 6, 8, 8, 8, 8, 8, 2, 1 ] * 1000000 | |
u = User.new( user_ids: array ) | |
x = 10000 | |
k = 3 | |
Benchmark.bm do |x| | |
[ 0, 1, 2, 3 ].each do |n| | |
start_time = Time.now | |
x.report("top_user_ids_#{ n }") { u.send("top_user_ids_#{ n }", k) } | |
puts "#{ "top_user_ids_#{ n }" } #{ Time.now - start_time }" | |
end | |
end | |
end | |
def self.benchmark_mem | |
array = [1,1, 3, 4, 6, 7,3, 1, 6, 8, 8, 8, 8, 8, 2, 1 ] * 1000000 | |
u = User.new( user_ids: array ) | |
x = 10000 | |
k = 3 | |
Benchmark.memory do |x| | |
[ 0, 1, 2, 3 ].each do |n| | |
x.report("top_user_ids_#{ n }") { u.send("top_user_ids_#{ n }", k) } | |
end | |
x.compare! | |
end | |
end | |
end | |
# User.benchmark | |
User.benchmark_mem | |
# User.test_a_method(3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment