using BenchmarkTools # sum(rand(N)) はメモリを大量消費 srand(2018) a(N) = sum(rand(N)) @show a(10^8) sleep(0.1) @benchmark a(10^8) # sum(rand() for i in 1:N) はメモリは節約するが sum(rand(N)) より遅い. srand(2018) b(N) = sum(rand() for i in 1:N) @show b(10^8) sleep(0.1) @benchmark b(10^8) # forループはメモリも消費ぜず速い srand(2018) c(N) = (s = 0.0; for i in 1:N s += rand() end; s) @show c(10^8) sleep(0.1) @benchmark c(10^8) # forループをマクロにすると @sum(0.0, _, 1:N, rand()) と短く書ける macro sum(init, i, iter, f) quote begin s = $(esc(init)) for $(esc(i)) in $(esc(iter)) s += $(esc(f)) end s end end end srand(2018) c_macro(N) = @sum(0.0, _, 1:N, rand()) @show c_macro(10^8) sleep(0.1) @benchmark c_macro(10^8) @show @sum(0, i, 1:10, @sum(0, j, 1:10, i*j)) @show sum(sum(i*j for j in 1:10) for i in 1:10) @macroexpand @sum(0, i, 1:10, @sum(0, j, 1:10, i*j)) # 並列処理するとさらに速くなる srand(2018) d(N) = @parallel (+) for i in 1:N rand() end @show d(10^8) sleep(0.1) @benchmark d(10^8) # 並列処理で和を計算するマクロ macro sum_parallel(i, iter, f) quote @parallel (+) for $(esc(i)) in $(esc(iter)); $(esc(f)); end end end srand(2018) d_macro(N) = @sum_parallel(_, 1:N, rand()) @show d_macro(10^8) sleep(0.1) @benchmark d_macro(10^8) @show @sum_parallel(i, 1:10, @sum_parallel(j, 1:10, i*j)) @show sum(sum(i*j for j in 1:10) for i in 1:10);