1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Julia 全部直接引数わたしと構造体わたし,どっちが早いか

Posted at

概要

Juliaで複数の配列を関数に渡すときに直接引数として渡すのと,構造体でまとめてから渡すので,どっちが早いか。

結論,変数が増えると構造体わたしのほうが遅い。

コード

using Parameters
using BenchmarkTools

@with_kw struct Param{T1}

    n::T1 = 100
end

struct vars
    u::Array{Float64, 2}
    v::Array{Float64, 2}
    p::Array{Float64, 2}
    T::Array{Float64, 2}
    u1::Array{Float64, 2}
    u2::Array{Float64, 2}
    u3::Array{Float64, 2}
end

#vars(para::Param) = vars(zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n))

function main(para)
    @unpack n = para

    u = zeros(Float64, n, n)
    v = zeros(Float64, n, n)
    p = zeros(Float64, n, n)
    T = zeros(Float64, n, n)
    u1 = zeros(Float64, n, n)
    u2 = zeros(Float64, n, n)
    u3 = zeros(Float64, n, n)

    #Var = vars(para)
    Var = vars(zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n), zeros(Float64, para.n, para.n))
    #Var = vars()

    @time for i=1:1000
        test_arg(para, u, v, p, T, u1, u2, u3)
    end
    println(u[1:5,1])
    @time for i=1:1000
        test_struct(para, Var)
    end
    println(Var.u[1:5,1])
end

function test_arg(para, u, v, p, T, u1, u2, u3)
    @unpack n = para 

    for j=1:n
        for i=1:n
            u[i,j] = 2*i+j*1.5
            v[i,j] = sin(i*j)
            p[i,j] = i-j*0.1 
            T[i,j] = 0.2i^2-j
            u1[i,j] = 0.2*i+j
            u2[i,j] = 0.2*i+j
            u3[i,j] = 0.2*i+j
        end
    end
end

function test_struct(para, Var)
    @unpack n = para 

    for j=1:n
        for i=1:n
            Var.u[i,j] = 2*i+j*1.5
            Var.v[i,j] = sin(i*j)
            Var.p[i,j] = i-j*0.1 
            Var.T[i,j] = 0.2i^2-j
            Var.u1[i,j] = 0.2*i+j
            Var.u2[i,j] = 0.2*i+j
            Var.u3[i,j] = 0.2*i+j
        end
    end
end

結果

julia> include("struct-arg-test.jl")
julia> para = Param(n=500)
julia> main(para)
 4.876456 seconds
[3.5, 5.5, 7.5, 9.5, 11.5]
  5.039125 seconds
[3.5, 5.5, 7.5, 9.5, 11.5]

前半が直接引数渡しで,後半が構造体で引数渡しの場合。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?