Skip to content

Instantly share code, notes, and snippets.

@shellac
Created June 28, 2012 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shellac/3012659 to your computer and use it in GitHub Desktop.
Save shellac/3012659 to your computer and use it in GitHub Desktop.
Branch prediction is detectable on jruby
require 'benchmark'
array_size = 32768
data = Array.new(array_size)
array_size.times { |c| data[c] = rand(256)}
data_sorted = data.sort
def sum(array)
sum = 0;
for i in 1..1000 # calm down, MRI is slooowwww
for j in 0..(array.size - 1)
sum += array[j] if array[j] >= 128
end
end
puts "Total: #{sum}"
end
puts 'Unsorted'
5.times { puts Benchmark.measure { sum(data) } }
puts 'Sorted'
5.times { puts Benchmark.measure { sum(data_sorted) } }
$ /usr/bin/ruby branch_predict.rb
Unsorted
Total: 3159277000
15.750000 0.020000 15.770000 ( 16.237136)
Total: 3159277000
15.900000 0.030000 15.930000 ( 16.129206)
Total: 3159277000
15.830000 0.010000 15.840000 ( 16.007797)
Total: 3159277000
15.810000 0.030000 15.840000 ( 16.122798)
Total: 3159277000
15.830000 0.020000 15.850000 ( 16.215970)
Sorted
Total: 3159277000
15.810000 0.030000 15.840000 ( 16.722894)
Total: 3159277000
15.790000 0.010000 15.800000 ( 15.894834)
Total: 3159277000
15.750000 0.010000 15.760000 ( 15.970007)
Total: 3159277000
15.800000 0.020000 15.820000 ( 16.326240)
Total: 3159277000
15.660000 0.020000 15.680000 ( 15.868698)
$ jruby branch_predict.rb
Unsorted
Total: 3154163000
2.920000 0.130000 3.050000 ( 2.761000)
Total: 3154163000
2.280000 0.010000 2.290000 ( 2.295000)
Total: 3154163000
2.290000 0.020000 2.310000 ( 2.316000)
Total: 3154163000
2.280000 0.010000 2.290000 ( 2.309000)
Total: 3154163000
2.310000 0.010000 2.320000 ( 2.357000)
Sorted
Total: 3154163000
2.150000 0.030000 2.180000 ( 2.239000)
Total: 3154163000
2.130000 0.000000 2.130000 ( 2.146000)
Total: 3154163000
2.110000 0.010000 2.120000 ( 2.120000)
Total: 3154163000
2.120000 0.010000 2.130000 ( 2.122000)
Total: 3154163000
2.140000 0.010000 2.150000 ( 2.116000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment