本帖最后由 guoxiaomi 于 2018-8-23 13:53 编辑
虽然不知道为什么,但是你这个程序算出来的- fast_pow(1.5, 3.0) = 3.395968437194824
- 1.5 ** 3.0 = 3.375
复制代码
测试了一下,其中fast_pow2是把第7和9行改成了 y = x % 1和 y = b % 1Benchmark.bm(10) do |t| t.report('**_pow'){ 1_000_000.times{1.5 ** 3.0} } t.report('fast_pow'){ 1_000_000.times{fast_pow(1.5, 3.0)} } t.report('fast_pow2'){ 1_000_000.times{fast_pow2(1.5, 3.0)} } a = 1.5 t.report('init_bits'){ 1_000_000.times{x = a.int_bits} } b = 3.0 y = 0.06197100837140948 t.report('get_from'){ 1_000_000.times{Float.get_from_int_bits(((b + 0x7f - y) * SHIFT23).to_i)} } end
Benchmark.bm(10) do |t|
t.report('**_pow'){
1_000_000.times{1.5 ** 3.0}
}
t.report('fast_pow'){
1_000_000.times{fast_pow(1.5, 3.0)}
}
t.report('fast_pow2'){
1_000_000.times{fast_pow2(1.5, 3.0)}
}
a = 1.5
t.report('init_bits'){
1_000_000.times{x = a.int_bits}
}
b = 3.0
y = 0.06197100837140948
t.report('get_from'){
1_000_000.times{Float.get_from_int_bits(((b + 0x7f - y) * SHIFT23).to_i)}
}
end
结果如下:user system total real
**_pow 0.093000 0.000000 0.093000 ( 0.092967)
fast_pow 2.485000 0.000000 2.485000 ( 2.485887)
fast_pow2 2.406000 0.000000 2.406000 ( 2.417023)
init_bits 0.625000 0.000000 0.625000 ( 0.621773)
get_from 1.453000 0.000000 1.453000 ( 1.463776)
user system total real
**_pow 0.093000 0.000000 0.093000 ( 0.092967)
fast_pow 2.485000 0.000000 2.485000 ( 2.485887)
fast_pow2 2.406000 0.000000 2.406000 ( 2.417023)
init_bits 0.625000 0.000000 0.625000 ( 0.621773)
get_from 1.453000 0.000000 1.453000 ( 1.463776)
|