对于大型类型的数组创建 NArray 可以更快,但对于小型数组创建(例如临时中间对象) Ruby Array 似乎更快更快。
基准代码:
require 'benchmark'
n1 = 1000000
n2 = 10000
Benchmark.bm do |x|
x.report("NArray short float length 5:") { n1.times { NArray.sfloat(5) } }
x.report("NArray long float length 5 :") { n1.times { NArray.float(5) } }
x.report("NArray short int length 5 :") { n1.times { NArray.sint(5) } }
x.report("NArray long int length 5 :") { n1.times { NArray.int(5) } }
x.report("NArray object length 5 :") { n1.times { NArray.object(5) } }
x.report("Ruby Array length 5 :") { n1.times { Array.new(5) } }
x.report("NArray short float length 10000:") { n2.times { NArray.sfloat(10000) } }
x.report("NArray long float length 10000 :") { n2.times { NArray.float(10000) } }
x.report("NArray short int length 10000 :") { n2.times { NArray.sint(10000) } }
x.report("NArray long int length 10000 :") { n2.times { NArray.int(10000) } }
x.report("NArray object length 10000 :") { n2.times { NArray.object(10000) } }
x.report("Ruby Array length 10000 :") { n2.times { Array.new(10000) } }
end
结果:
user system total real
NArray short float length 5: 0.740000 0.020000 0.760000 ( 0.756466)
NArray long float length 5 : 0.770000 0.020000 0.790000 ( 0.791446)
NArray short int length 5 : 0.750000 0.020000 0.770000 ( 0.772591)
NArray long int length 5 : 0.760000 0.020000 0.780000 ( 0.777375)
NArray object length 5 : 0.780000 0.020000 0.800000 ( 0.801149)
Ruby Array length 5 : 0.450000 0.010000 0.460000 ( 0.461501) <====
NArray short float length 10000: 0.230000 0.050000 0.280000 ( 0.281369)
NArray long float length 10000 : 0.430000 0.000000 0.430000 ( 0.428917)
NArray short int length 10000 : 0.110000 0.010000 0.120000 ( 0.113683)
NArray long int length 10000 : 0.230000 0.040000 0.270000 ( 0.275942)
NArray object length 10000 : 0.460000 0.110000 0.570000 ( 0.570558)
Ruby Array length 10000 : 0.440000 0.040000 0.480000 ( 0.476690)