首页 > 代码库 > julia的优化?
julia的优化?
julia> function fib1(n) if n==1 return n else return n+fib1(n-1) end end fib1 (generic function with 1 method) julia> function fib2(n,s) if n == 1 return s+1 else return fib2(n-1,s+n) end end fib2 (generic function with 1 method) julia> fib1(10) 55 julia> fib2(10) ERROR: MethodError: no method matching fib2(::Int64) Closest candidates are: fib2(::Any, ::Any) at REPL[18]:2 julia> fib2(10,0) 55 julia> fib2(20) ERROR: MethodError: no method matching fib2(::Int64) Closest candidates are: fib2(::Any, ::Any) at REPL[18]:2 julia> fib2(20,0) 210 julia> fib1(20) 210 julia> time(fib1(100)) ERROR: MethodError: no method matching time(::Int64) Closest candidates are: time() at libc.jl:206 time(::Base.Libc.TmStruct) at libc.jl:205 julia> @time(fib1(100)) 0.000005 seconds (131 allocations: 7.734 KB) 5050 julia> @time(fib2(100,0)) 0.000007 seconds (5 allocations: 176 bytes) 5050 julia> @time(fib1(500)) 0.000005 seconds (5 allocations: 176 bytes) 125250 julia> @time(fib2(500,0)) 0.000010 seconds (5 allocations: 176 bytes) 125250 julia> @time(fib1(1000)) 0.000022 seconds (5 allocations: 176 bytes) 500500 julia> @time(fib2(1000,0)) 0.000009 seconds (5 allocations: 176 bytes) 500500 julia> @time(fib1(10000)) 0.000325 seconds (5 allocations: 176 bytes) 50005000 julia> @time(fib2(10000,0)) 0.000095 seconds (5 allocations: 176 bytes) 50005000
julia> code_native(fib1,(Int64,))
.text
Filename: REPL[17]
pushq %rbp
movq %rsp, %rbp
pushq %rsi
subq $40, %rsp
movq %rcx, %rsi
Source line: 2
cmpq $1, %rsi
jne L30
Source line: 3
movl $1, %eax
addq $40, %rsp
popq %rsi
popq %rbp
retq
Source line: 5
L30:
leaq -1(%rsi), %rcx
movabsq $fib1, %rax
callq *%rax
addq %rsi, %rax
addq $40, %rsp
popq %rsi
popq %rbp
retq
nopl (%rax,%rax)
julia> code_native(fib2,(Int64,Int64))
.text
Filename: REPL[18]
pushq %rbp
movq %rsp, %rbp
Source line: 2
subq $32, %rsp
cmpq $1, %rcx
jne L26
Source line: 3
incq %rdx
movq %rdx, %rax
addq $32, %rsp
popq %rbp
retq
Source line: 5
L26:
addq %rcx, %rdx
decq %rcx
movabsq $fib2, %rax
callq *%rax
addq $32, %rsp
popq %rbp
retq
nopw %cs:(%rax,%rax)
尾递归版应该是有优化的啊,为什么内存和执行时间都没明显差别?
julia的优化?