为什么我的Julia代码运行速度比javascript慢? [英] Why my Julia code runs slower than javascript?

查看:109
本文介绍了为什么我的Julia代码运行速度比javascript慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我对Julia-lang感兴趣,因为它声称是一种动态语言,具有接近C的性能.但是,到目前为止,我的经验还不够好(至少从性能角度而言). 我正在编写的应用程序需要随机访问特定的数组索引,然后将它们的值与其他特定的数组索引进行比较(经过多次迭代).以下代码从程序中模拟了我的需求: 我的Julia代码在大约8秒内完成执行,而在chrome环境中,Java脚本代码所需的时间不到1秒! 我的Julia代码有问题吗?提前非常感谢.

Recently, I was intrigued by the Julia-lang as it claims to be a dynamic language that has near C performance. However, my experience with it so far is not good (at least performance wise). The application that I'm writing requires random-access to specific array indices and then comparing their values with other specific array indices (over many iterations). The following code simulates my needs from the program: My Julia code finishes executing in around 8seconds while the java-script code requires less than 1second on chrome environment! Am I doing something wrong with the Julia code? Thanks a lot in advance.

朱莉娅代码在这里:

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倍!)

Javascript code: (>8 times faster than the julia code above!)

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');

推荐答案

性能提示

避免全局变量

全局变量可能会改变其值,因此其类型也会改变 在任何时候.这使编译器难以优化 使用全局变量的代码.变量应为局部变量,或以 函数的参数.

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)

这篇关于为什么我的Julia代码运行速度比javascript慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆