Asc*_*hen 2 performance crystal-lang
我运行了这个基准测试,我很惊讶地发现,对于 Int32 或 Float64 操作,Crystal 性能几乎相同。
$ crystal benchmarks/int_vs_float.cr --release
int32 414.96M ( 2.41ns) (±14.81%) 0.0B/op fastest
float64 354.27M ( 2.82ns) (±12.46%) 0.0B/op 1.17× slower
Run Code Online (Sandbox Code Playgroud)
我的基准代码是否有一些奇怪的副作用?
require "benchmark"
res = 0
res2 = 0.0
Benchmark.ips do |x|
x.report("int32") do
a = 128973 / 119236
b = 119236 - 128973
d = 117232 > 123462 ? 117232 * 123462 : 123462 / 117232
res = a + b + d
end
x.report("float64") do
a = 1.28973 / 1.19236
b = 1.19236 - 1.28973
d = 1.17232 > 1.23462 ? 1.17232 * 1.23462 : 1.23462 / 1.17232
res = a + b + d
end
end
puts res
puts res2
Run Code Online (Sandbox Code Playgroud)
首先/在 Crystal 中是浮点除法,所以这主要是比较浮点数:
typeof(a) # => Float64
typeof(b) # => Int32
typeof(d) # => Float64 | Int32)
Run Code Online (Sandbox Code Playgroud)
如果我们修复基准以使用整数除法//,我得到:
int32 631.35M ( 1.58ns) (± 5.53%) 0.0B/op 1.23× slower
float64 773.57M ( 1.29ns) (± 3.21%) 0.0B/op fastest
Run Code Online (Sandbox Code Playgroud)
在误差范围内仍然没有真正的区别。为什么?让我们深入挖掘。首先,我们可以将示例提取到一个不可内联的函数中,并确保调用它,这样 Crystal 就不会忽略它:
@[NoInline]
def calc
a = 128973 // 119236
b = 119236 - 128973
d = 117232 > 123462 ? 117232 * 123462 : 123462 // 117232
a + b + d
end
p calc
Run Code Online (Sandbox Code Playgroud)
然后我们可以构建它crystal build --release --no-debug --emit llvm-ir以获得一个带有.ll优化的 LLVM-IR的文件。我们挖掘出我们的calc函数并看到如下内容:
define i32 @"*calc:Int32"() local_unnamed_addr #19 {
alloca:
%0 = tail call i1 @llvm.expect.i1(i1 false, i1 false)
br i1 %0, label %overflow, label %normal6
overflow: ; preds = %alloca
tail call void @__crystal_raise_overflow()
unreachable
normal6: ; preds = %alloca
ret i32 -9735
}
Run Code Online (Sandbox Code Playgroud)
我们所有的计算都去哪儿了?LLVM 在编译时完成了它们,因为它们都是常量!我们可以用Float64例子重复这个实验:
define double @"*calc:Float64"() local_unnamed_addr #11 {
alloca:
ret double 0x40004CAA3B35919C
}
Run Code Online (Sandbox Code Playgroud)
少一点样板,因此它稍微快一点,但同样,都是预先计算的!
我将在这里结束练习。供读者进一步研究: