Why Julia?

Or: DIRHTLYAPL

("Do I Really Have To Learn Yet Another Programming Language??")

Kyle Barbary

Cosmology Data Science Fellow
UC-Berkeley, LBNL

Twitter: @kylebarbary
GitHub: @kbarbary

Thanks to David P. Sanders for title, inspiration and much content.
See his Julia tutorial at SciPy 2014 here: https://github.com/dpsanders/scipy_2014_julia

Advantage of Julia

  • High-level and easy to learn
  • Fast (within ~2x C speed)

Avoids the "two language problem" (most of the standard library is written in Julia: "users are developers")


In [1]:
function calculate_pi(n)
    tot = 0
    for i = 1:n
        x = rand()
        y = rand()
        if x^2 + y^2 < 1.0
            tot += 1
        end
    end
    return 4.0 * (tot / n)
end


Out[1]:
calculate_pi (generic function with 1 method)

In [6]:
calculate_pi(1000000.0)


Out[6]:
3.141092

In [4]:
@time calculate_pi(1000000)


elapsed time: 0.018396916 seconds (96 bytes allocated)
Out[4]:
3.142772

How?

Code is compiled to native machine code just-in-time (JIT).

  • Functions are compiled for the specific input type(s)
  • You can write a function once and have it apply multiple input types: "generic programming"
  • Just like a compiled language, the compiler can perform optimizations

In [5]:
code_native(calculate_pi, (Int,))


	.text
Filename: In[1]
Source line: 4
	push	RBP
	mov	RBP, RSP
	push	R15
	push	R14
	push	R12
	push	RBX
	sub	RSP, 16
	mov	R14, RDI
	xor	R12D, R12D
	test	R14, R14
	jle	87
	movabs	R15, 139652734009248
	movabs	RAX, 139652836456976
	movsd	XMM0, QWORD PTR [RAX]
	movsd	QWORD PTR [RBP - 48], XMM0
	mov	RBX, R14
Source line: 4
	call	R15
	movsd	QWORD PTR [RBP - 40], XMM0
Source line: 5
	call	R15
	movsd	XMM1, QWORD PTR [RBP - 40]
Source line: 6
	mulsd	XMM1, XMM1
	mulsd	XMM0, XMM0
	addsd	XMM0, XMM1
	movsd	XMM1, QWORD PTR [RBP - 48]
	ucomisd	XMM1, XMM0
	jbe	3
Source line: 7
	inc	R12
	dec	RBX
	jne	-55
Source line: 10
	xorps	XMM1, XMM1
	cvtsi2sd	XMM1, R14
	xorps	XMM0, XMM0
	cvtsi2sd	XMM0, R12
	divsd	XMM0, XMM1
	movabs	RAX, 139652836456984
	mulsd	XMM0, QWORD PTR [RAX]
	add	RSP, 16
	pop	RBX
	pop	R12
	pop	R14
	pop	R15
	pop	RBP
	ret

More on Julia

  • has a sophisticated type system (but it is not necessary to talk about types)

  • has multiple dispatch: functions specialised on the types of their arguments

  • has sophisticated metaprogramming (macros) for generating code programatically

  • call compiled C or Fortran code directly. No wrappers needed. Same function overhead as in C.

Using Julia

  • From the REPL (Read--Eval--Print Loop):

      julia
  • Inside IJulia (IPython/Jupyter interface with Julia kernel):

      ipython notebook --profile julia
  • Scripts:

      julia scriptname.jl arg1 arg2

Learning and Getting help