Skip to content

Instantly share code, notes, and snippets.

@fxn
Last active May 10, 2024 20:36
Show Gist options
  • Save fxn/a1f3df52e260845e1efb09a58b7f2527 to your computer and use it in GitHub Desktop.
Save fxn/a1f3df52e260845e1efb09a58b7f2527 to your computer and use it in GitHub Desktop.
# crystal build foo.cr --release
# ./foo 37.7749 -122.4194 34.0522 -118.2437
#
# Around 0.08s.
module GeoCalculator
EARTH_RADIUS_IN_KM = 6371.0
def self.distance(lat1, lon1, lat2, lon2)
dlat = lat2 - lat1
dlon = lon2 - lon1
a = Math.sin(dlat/2.0)**2 + Math.cos(lat1)*Math.cos(lat2)* Math.sin(dlon/2.0)**2
c = 2*Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
c*EARTH_RADIUS_IN_KM
end
end
lat1, lon1, lat2, lon2 = ARGV.map(&.to_f)
d = 0
puts Time.measure {
i = 0
while i < 10_000_000
d += GeoCalculator.distance(lat1, lon1, lat2, lon2)
i += 1
end
}
puts d
# ruby foo.rb 37.7749 -122.4194 34.0522 -118.2437
#
# Around 1.92s.
require 'benchmark'
module GeoCalculator
EARTH_RADIUS_IN_KM = 6371.0
def self.distance(lat1, lon1, lat2, lon2)
dlat = lat2 - lat1
dlon = lon2 - lon1
a = Math.sin(dlat/2.0)**2 + Math.cos(lat1)*Math.cos(lat2)*Math.sin(dlon/2.0)**2
c = 2*Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
c*EARTH_RADIUS_IN_KM
end
end
lat1, lon1, lat2, lon2 = ARGV.map(&:to_f)
d = 0
puts Benchmark.measure {
i = 0
while i < 10_000_000
d += GeoCalculator.distance(lat1, lon1, lat2, lon2)
i += 1
end
}
puts d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment