Created
May 21, 2017 15:29
-
-
Save meagar/2711806c624f5fa600093dd18ae6789a to your computer and use it in GitHub Desktop.
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
# benchmark for http://stackoverflow.com/q/44097717/229044 | |
require 'set' | |
require 'benchmark' | |
def make_data(size = 25_000) | |
t = Time.now | |
size.downto(0).map do |i| | |
{ | |
'timestamp-value' => (t - i * 60).to_s[0..15], | |
'value' => i | |
} | |
end | |
end | |
X_DATA = make_data.freeze | |
Y_DATA = make_data.freeze | |
N = 100 | |
def values_for_regression(x_data, y_data) | |
x_timestamps = timestamps_for(x_data) | |
y_timestamps = timestamps_for(y_data) | |
# Get final timestamps as the intersection of the two | |
timestamps = x_timestamps.intersection(y_timestamps) | |
x_values = values_for(x_data, timestamps) | |
y_values = values_for(y_data, timestamps) | |
[x_values, y_values] | |
end | |
def timestamps_for(data) | |
Set.new data.reject { |row| row['value'].nil? }.map { |row| row['timestamp-value'] } | |
end | |
def values_for(data, timestamps) | |
data.select { |row| timestamps.include?(row['timestamp-value']) }.map { |row| row['value'] } | |
end | |
def my_values_for_regression(x_data, y_data) | |
x_values = [] | |
y_values = [] | |
y_map = y_data.each_with_object({}) { |data, hash| hash[data['timestamp-value']] = data['value'] } | |
x_data.each do |data| | |
next unless x_value = data['value'] | |
next unless y_value = y_map[data['timestamp-value']] | |
x_values << x_value | |
y_values << y_value | |
end | |
[x_values, y_values] | |
end | |
yours = values_for_regression(X_DATA, Y_DATA) | |
mine = my_values_for_regression(X_DATA, Y_DATA) | |
unless yours[0] == mine[0] && yours[1] == mine[1] | |
raise("Output doesn't match!") | |
end | |
Benchmark.bm(10) do |bm| | |
bm.report 'yours' do | |
N.times { values_for_regression(X_DATA, Y_DATA) } | |
end | |
bm.report 'mine' do | |
N.times { my_values_for_regression(X_DATA, Y_DATA) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment