最近,我对Julia-lang感兴趣,因为它声称它是一种具有接近C性能的动态语言.但是,到目前为止我对它的体验并不好(至少表现明智). 我正在编写的应用程序需要随机访问特定的数组索引,然后
我正在编写的应用程序需要随机访问特定的数组索引,然后将它们的值与其他特定的数组索引进行比较(通过多次迭代).以下代码模拟了我对程序的需求:
我的Julia代码在大约8秒内完成执行,而 java脚本代码在chrome环境中需要不到1秒!
我是否在使用Julia代码做错了什么?非常感谢提前.
朱莉娅代码在这里:
n=5000; x=rand(n) y=rand(n) mn=ones(n)*1000; tic(); for i in 1:n; for j in 1:n; c=abs(x[j]-y[i]); if(c<mn[i]) mn[i]=c; end end end toc();
Javascript代码:(>比上面的julia代码快8倍!)
n=5000; x=[]; y=[]; mn=[]; for(var i=0; i<n; i++){x.push(Math.random(1))} for(var i=0; i<n; i++){y.push(Math.random(1))} for(var i=0; i<n; i++){mn.push(1000)} console.time('test'); for(var i=0; i<n; i++){ for(var j=0; j<n; j++){ c=Math.abs(x[j]-y[i]); if(c<mn[i]){ mn[i]=c; } } } console.timeEnd('test');Performance Tips
Avoid global variables
A global variable might have its value, and therefore its type, change
at any point. This makes it difficult for the compiler to optimize
code using global variables. Variables should be local, or passed as
arguments to functions, whenever possible.Any code that is performance critical or being benchmarked should be
inside a function.We find that global names are frequently constants, and declaring them
as such greatly improves performance:
julia> const n = 5000; const x, y = rand(n), rand(n); const mn = fill(1000.0, n); julia> function foo!(mn, x, y) n = length(mn) @inbounds for i in 1:n, j in 1:n c = abs(x[j] - y[i]) if(c < mn[i]) mn[i] = c end end return mn end foo! (generic function with 1 method) julia> using BenchmarkTools: @btime julia> @btime foo!(mn, x, y) 15.432 ms (0 allocations: 0 bytes)