Home Programming Getting Started with Julia

Getting Started with Julia

By Ivo Balbaert
books-svg-icon Book
eBook $25.99 $17.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $25.99 $17.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Installing the Julia Platform
About this book
Publication date:
February 2015
Publisher
Packt
Pages
214
ISBN
9781783284795

 

Chapter 1. Installing the Julia Platform

This chapter guides you through the download and installation of all the necessary components of Julia. The topics covered in this chapter are as follows:

  • Installing Julia

  • Working with Julia's shell

  • Start-up options and Julia scripts

  • Packages

  • Installing and working with Julia Studio

  • Installing and working with IJulia

  • Installing Sublime-IJulia

  • Installing Juno

  • Other editors and IDEs

  • Working of Julia

By the end of this chapter, you will have a running Julia platform. Moreover, you will be able to work with Julia's shell as well as with editors or integrated development environments with a lot of built-in features to make development more comfortable.

 

Installing Julia


The Julia platform in binary (that is, executable) form can be downloaded from http://julialang.org/downloads/. It exists for three major platforms (Windows, Linux, and OS X) in 32- and 64-bit format, and is delivered as a package or in an archive format. You should use the current official stable release when doing serious professional work with Julia (at the time of writing, this is Version 0.3). If you would like to investigate the latest developments, install the upcoming version (which is now Version 0.4). The previous link contains detailed and platform-specific instructions for the installation. We will not repeat these instructions here completely, but we will summarize some important points.

Windows version – usable from Windows XP SP2 onwards

You need to keep the following things in mind if you are using the Windows OS:

  1. As a prerequisite, you need the 7zip extractor program, so first download and install http://www.7-zip.org/download.html.

  2. Now, download the julia-n.m.p-win64.exe file to a temporary folder (n.m.p is the version number, such as 0.2.1 or 0.3.0; win32/win64 are respectively the 32- and 64-bit version; a release candidate file looks like julia-0.4.0-rc1-nnnnnnn-win64 (nnnnnnn is a checksum number such as 0480f1b).

  3. Double-click on the file (or right-click, and select Run as Administrator if you want Julia installed for all users on the machine). Clicking OK on the security dialog message, and then choosing the installation directory (for example, c:\julia) will extract the archive into the chosen folder, producing the following directory structure, and taking some 400 MB of disk space:

    The Julia folder structure in Windows

  4. A menu shortcut will be created which, when clicked, starts the Julia command-line version or Read Evaluate Print Loop (REPL), as shown in the following screenshot:

    The Julia REPL

  5. On Windows, if you have chosen C:\Julia as your installation directory, this is the C:\Julia\bin\julia.exe file. Add C:\Julia\bin to your PATH variable if you want the REPL to be available on any Command Prompt. The default installation folder on Windows is: C:\Users\UserName\AppData\Local\Julia-n.m.p (where n.m.p is the version number, such as 0.3.2).

  6. More information on Julia in the Windows OS can be found at https://github.com/JuliaLang/julia/blob/master/README.windows.md.

Ubuntu version

For Ubuntu systems (Version 12.04 or later), there is a Personal Package Archive (PPA) for Julia (can be found at https://launchpad.net/~staticfloat/+archive/ubuntu/juliareleases) that makes the installation painless. All you need to do to get the stable version is to issue the following commands in a terminal session:

sudo add-apt-repository ppa:staticfloat/juliareleases
sudo add-apt-repository ppa:staticfloat/julia-deps
sudo apt-get update
sudo apt-get install julia

If you want to be at the bleeding edge of development, you can download the nightly builds instead of the stable releases. The nightly builds are generally less stable, but will contain the most recent features. To do so, replace the first of the preceding commands with:

sudo add-apt-repository ppa:staticfloat/julianightlies

This way, you can always upgrade to a more recent version by issuing the following commands:

sudo apt-get update
sudo apt-get upgrade

The Julia executable lives in /usr/bin/julia (given by the JULIA_HOME variable or by the which julia command) and the standard library is installed in /usr/share/julia/base, with shared libraries in /usr/lib/x86_64-linux-gnu/Julia.

For other Linux versions, the best way to get Julia running is to build from source (refer to the next section).

OS X

Installation for OS X is straightforward—using the standard software installation tools for the platform. Add /Applications/Julia-n.m.app/Contents/Resources/julia/bin/Julia to make Julia available everywhere on your computer.

If you want code to be run whenever you start a Julia session, put it in /home/.juliarc.jl on Ubuntu, ~/.juliarc.jl on OS X, or c:\Users\username\.juliarc.jl on Windows. For instance, if this file contains the following code:

println("Greetings! 你好! 안녕하세요?")

Then, Julia starts up in its shell (or REPL as it is usually called) with the following text in the screenshot, which shows its character representation capabilities:

Using .juliarc.jl

Building from source

Perform the following steps to build Julia from source:

  1. Download the source code, rather than the binaries, if you intend to contribute to the development of Julia itself, or if no Julia binaries are provided for your operating system or particular computer architecture. Building from source is quite straightforward on Ubuntu, so we will outline the procedure here. The Julia source code can be found on GitHub at https://github.com/JuliaLang/julia.git.

  2. Compiling these will get you the latest Julia version, not the stable version (if you want the latter, download the binaries, and refer to the previous section).

  3. Make sure you have git installed; if not, issue the command:

    sudo apt-get -f install git
    
  4. Then, clone the Julia sources with the following command:

    git clone git://github.com/JuliaLang/julia.git
    

    This will download the Julia source code into a julia directory in the current folder.

  5. The Julia building process needs the GNU compilation tools g++, gfortran, and m4, so make sure that you have installed them with the following command:

    sudo apt-get install gfortran g++ m4
    
  6. Now go to the Julia folder and start the compilation process as follows:

    cd julia
    make
    
  7. After a successful build, Julia starts up with the ./julia command.

  8. Afterwards, if you want to download and compile the newest version, here are the commands to do this in the Julia source directory:

    git pull
    make clean
    make
    

For more information on how to build Julia on Windows, OS X, and other systems, refer to https://github.com/JuliaLang/julia/.

Tip

Using parallelization

If you want Julia to use n concurrent processes, compile the source with make -j n.

There are two ways of using Julia. As described in the previous section, we can use the Julia shell for interactive work. Alternatively, we can write programs in a text file, save them with a .jl extension, and let Julia execute the whole program sequentially.

 

Working with Julia's shell


We started with Julia's shell in the previous section (refer to the preceding two screenshots) to verify the correctness of the installation, by issuing the julia command in a terminal session. The shell or REPL is Julia's working environment, where you can interact with the Just in Time (JIT) compiler to test out pieces of code. When satisfied, you can copy and paste this code into a file with a .jl extension, such as program.jl. Alternatively, you can continue the work on this code from within a text editor or an IDE, such as the ones we will point out later in this chapter. After the banner with Julia's logo has appeared, you get a julia> prompt for the input. To end this session, and get to the OS Command Prompt, type CTRL + D or quit(), and hit ENTER. To evaluate an expression, type it and press ENTER to show the result, as shown in the following screenshot:

Working with the REPL (1)

If, for some reason, you don't need to see the result, end the expression with a ; (semicolon) such as 6 * 7. In both the cases, the resulting value is stored, for convenience, in a variable named ans that can be used in expressions, but only inside the REPL. You can bind a value to a variable by entering an assignment as a = 3. Julia is dynamic, and we don't need to enter a type for a, but we do need to enter a value for the variable, so that Julia can infer its type. Using a variable b that is not bound to the a value, results in the ERROR: b not defined message. Strings are delineated by double quotes (""), as in b = "Julia". The following screenshot illustrates these workings with the REPL:

Working with the REPL (2)

Previous expressions can be retrieved in the same session by working with the up and down arrow keys. The following key bindings are also handy:

  • To clear or interrupt a current command, press CTRL + C

  • To clear the screen (but variables are kept in memory), press CTRL + L

  • To reset the session so that variables are cleared, enter the command workspace() in the REPL

Commands from the previous sessions can still be retrieved, because they are stored (with a timestamp) in a.julia_history file (in /home/$USER on Ubuntu, c:\Users\username on Windows, or ~/.julia_history on OS X). Ctrl + R (produces a (reverse-i-search) ': prompt) searches through these commands.

Typing ? starts up the help mode (help?>) to give quick access to Julia's documentation. Information on function names, types, macros, and so on, is given when typing in their name. Alternatively, to get more information on a variable a, type help(a), and to get more information on a function such as sort, type help(sort). To find all the places where a function such as println is defined or used, type apropos("println"), which gives the following output:

Base.println(x)
Base.enumerate(iter)
Base.cartesianmap(f, dims)

Thus, we can see that it is defined in the Base module, and is used in two other functions. Different complete expressions on the same line have to be separated by a ; (semicolon) and only the last result is shown. You can enter multi-line expressions as shown in the following screenshot. If the shell detects that the statement is syntactically incomplete, it will not attempt to evaluate it. Rather, it will wait for the user to enter additional lines until the multi-line statement can be evaluated.

Working with the REPL (3)

A handy autocomplete feature also exists. Type one or more letters, press the Tab key twice, and then a list of functions starting with these letters appears. For example: type so, press the Tab key twice, and then you get the list as: sort sort! sortby sortby! sortcols sortperm sortrows.

If you start a line with ;, the rest of the line is interpreted as a system shell command (try for example, ls, cd, mkdir, whoami, and so on). The Backspace key returns to the Julia prompt.

A Julia script can be executed in the REPL by calling it with include. For example, for hello.jl, which contains the println("Hello, Julia World!") command, the command is as follows:

julia> include("hello.jl")

The preceding command prints the output as follows:

  Hello, Julia World!

Experiment a bit with different expressions to get some feeling for this environment.

 

Startup options and Julia scripts


Without any options, the julia command starts up the REPL environment. A useful option to check your environment is julia –v. This shows Julia's version, for example, julia-version 0.3.2+2. (The versioninfo()function in REPL is more detailed, the VERSION constant gives you only the version number: v"0.3.2+2"). An option that lets you evaluate expressions on the command line itself is –e, for example:

  julia -e 'a = 6 * 7;
  println(a)'

The preceding commands print out 42 (on Windows, use " instead of the ' character).

Some other options useful for parallel processing will be discussed in Chapter 9, Running External Programs. Type julia –h for a list of all options.

A script.jl file with Julia source code can be started from the command line with the following command:

julia script.jl arg1 arg2 arg3

Here arg1, arg2, and arg3 are optional arguments to be used in the script's code. They are available from the global constant ARGS. Take a look at the args.jl file as follows:

for arg in ARGS
  println(arg)
end

The julia args.jl 1 Dart C command prints out 1, Dart, and C on consecutive lines.

A script file also can execute other source files by including them in the REPL; for example, main.jl contains include("hello.jl") that will execute the code from hello.jl when called with julia main.jl.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

 

Packages


Most of the standard library in Julia (can be found in /share/julia/base relative to where Julia was installed) is written in Julia itself. The rest of Julia's code ecosystem is contained in packages that are simply Git repositories. They are most often authored by external contributors, and already provide functionality for such diverse disciplines such as bioinformatics, chemistry, cosmology, finance, linguistics, machine learning, mathematics, statistics, and high-performance computing. A searchable package list can be found at http://pkg.julialang.org/. Official Julia packages are registered in the METADATA.jl file in the Julia Git repository, available on GitHub at https://github.com/JuliaLang/METADATA.jl.

Julia's installation contains a built-in package manager Pkg for installing additional Julia packages written in Julia. The downloaded packages are stored in a cache ready to be used by Julia given by Pkg.dir(), which are located at c:\users\username\.julia\vn.m\.cache, /home/$USER/.julia/vn.m/.cache, or ~/.julia/vn.m/.cache. If you want to check which packages are installed, run the Pkg.status() command in the Julia REPL, to get a list of packages with their versions, as shown in the following screenshot:

Packages list

The Pkg.installed() command gives you the same information, but in a dictionary form and is usable in code. Version and dependency management is handled automatically by Pkg. Different versions of Julia can coexist with incompatible packages, each version has its own package cache.

Tip

If you get an error with Pkg.status() such as ErrorException("Unable to read directory METADATA."), issue a Pkg.init() command to create the package repository folders, and clone METADATA from Git. If the problem is not easy to find or the cache becomes corrupted somehow, you can just delete the .julia folder, enter Pkg.init(), and start with an empty cache. Then, add the packages you need.

Adding a new package

Before adding a new package, it is always a good idea to update your package database for the already installed packages with the Pkg.update()command. Then, add a new package by issuing the Pkg.add("PackageName") command, and execute using PackageName in code or in the REPL. For example, to add 2D plotting capabilities, install the Winston package with Pkg.add("Winston "). To make a graph of 100 random numbers between 0 and 1, execute the following commands:

using Winston
plot(rand(100))

The rand(100) function is an array with 100 random numbers. This produces the following output:

A plot of white noise with Winston

After installing a new Julia version, update all the installed packages by running Pkg.update() in the REPL. For more detailed information, you can refer to http://docs.julialang.org/en/latest/manual/packages/.

 

Installing and working with Julia Studio


Julia Studio is a free desktop app for working with Julia that runs on Linux, Windows, and OS X (http://forio.com/labs/julia-studio/). It works with the 0.3 release on Windows (Version 0.2.1 for Linux and OS X, at this time, if you want Julia Studio to work with Julia v0.3 on Linux and OS X, you have to do the compilation of the source code of the Studio yourself). It contains a sophisticated editor and integrated REPL, version control with Git, and a very handy side pane with access to the command history, filesystem, packages, and the list of edited documents. It is created by Forio, a company that makes software for simulations, data explorations, interactive learning, and predictive analytics. In the following screenshot, you can see some of Julia Studio's features, such as the Console section and the green Run button (or F5) in the upper-right corner. The simple program fizzbuzz.jl prints for the first 100 integers for "fizz" if the number is a multiple of 3, "buzz" if a multiple of 5, and "fizzbuzz" if it is a multiple of 15.

Julia Studio

Notice the # sign that indicates the beginning of comments, the elegant and familiar for loop and if elseif construct, and how they are closed with end. The 1:100 range is a range; mod returns the remainder of the division; the function mod(i, n) can also be written as an i % n operator. Using four spaces for indentation is a convention. Recently, Forio also developed Epicenter, a computational platform for hosting the server-side models (also in Julia), and building interactive web interfaces for these models.

 

Installing and working with IJulia


IJulia (https://github.com/JuliaLang/IJulia.jl) is a combination of the IPython web frontend interactive environment (http://ipython.org/) with a Julia-language backend. It allows you to work with IPython's powerful graphical notebook (which combines code, formatted text, math, and multimedia in a single document) with qtconsole and regular REPL. Detailed instructions for installation are found at the GitHub page for IJulia (https://github.com/JuliaLang/IJulia.jl) and in the Julia at MIT notes (https://github.com/stevengj/julia-mit/blob/master/README.md). Here is a summary of the steps:

  1. Install Version 1.0 or later of IPython via easy_install or pip (on OS X and Windows, this is included in the Anaconda Python installation). On Linux, use apt-get install ipython. (For more information, refer to the IPython home page).

  2. Install PyQt4 or PySide for qtconsole.

  3. Install the IJulia package from the REPL with Pkg.add("IJulia").

  4. Install the PyPlot package with Pkg.add("PyPlot").

You can work with IJulia in either of two ways:

  • Start an IPython notebook in your web browser by typing the following command in a console:

    ipython notebook --profile julia
    
  • Start qtconsole with:

    ipython qtconsole --profile Julia
    

The IJulia dashboard on Ubuntu

Verify that you have started IJulia. You must see IJ and the Julia logo in the upper-left corner of the browser window. Julia code is entered in the input cells (input can be multiline) and then executed with Shift + Enter. Here is a small example:

An IJulia session example

In the first input cell, the value of b is calculated from a:

a = 5
b = 2a^2 + 30a + 9

In the second input cell, we use PyPlot (this requires the installation of matplotlib; for example, on Linux, this is done by sudo apt-get install python-matplotlib).

The linspace(0, 5) command defines an array of 100 equally spaced values between 0 and 5, y is defined as a function of x and is then shown graphically with the plot as follows:

using PyPlot
x = linspace(0, 5)
y = cos(2x + 5)
plot(x, y, linewidth=2.0, linestyle="--")
title("a nice cosinus")
xlabel("x axis")
ylabel("y axis")

Save a notebook in file format (with the extension .ipynb) by downloading it from the menu. If working in an IPython notebook is new for you, you can take a look at the demo at http://ipython.org/notebook.html to get started. After installing a new Julia version, always run Pkg.build("IJulia") in the REPL in order to rebuild the IJulia package with this new version.

 

Installing Sublime-IJulia


The popular Sublime Text editor (http://www.sublimetext.com/3) now has a plugin based on IJulia (https://github.com/quinnj/Sublime-IJulia) authored by Jacob Quinn. It gives you syntax highlighting, autocompletion, and an in-editor REPL, which you basically just open like any other text file, but it runs Julia code for you. You can also select some code from a code file and send it to the REPL with the shortcut CTRL + B, or send the entire file there. Sublime-IJulia provides a frontend to the IJulia backend kernel, so that you can start an IJulia frontend in a Sublime view and interact with the kernel. Here is a summary of the installation, for details you can refer to the preceding URL:

  1. From within the Julia REPL, install the ZMQ and IJulia packages.

  2. From within Sublime Text, install the Package Control package (https://sublime.wbond.net/installation).

  3. From within Sublime Text, install the IJulia package from the Sublime command palette.

  4. Ctrl + Shift + P opens up a new IJulia console. Start entering commands, and press Shift + Enter to execute them. The Tab key provides command completion.

 

Installing Juno


Another promising IDE for Julia and a work in progress by Mike Innes and Keno Fisher is Juno, which is based on the Light Table environment. The docs at http://junolab.org/docs/installing.html provides detailed instructions for installing and configuring Juno. Here is a summary of the steps:

  1. Get LightTable from http://lighttable.com.

  2. Start LightTable, install the Juno plugin through its plugin manager, and restart LightTable.

Light Table works extensively with a command palette that you can open by typing Ctrl + SPACE, entering a command, and then selecting it. Juno provides an integrated console, and you can evaluate single expressions in the code editor directly by typing Ctrl + Enter at the end of the line. A complete script is evaluated by typing Ctrl + Shift + Enter.

 

Other editors and IDEs


For terminal users, the available editors are as follows:

On Linux, gedit is very good. The Julia plugin works well and provides autocompletion. Notepad++ also has Julia support from the contrib directory mentioned earlier.

The SageMath project (https://cloud.sagemath.com/) runs Julia in the cloud within a terminal and lets you work with IPython notebooks. You can also work and teach with Julia in the cloud using the JuliaBox platform (https://juliabox.org/).

 

How Julia works


(You can safely skip this section on a first reading.)

Julia works with an LLVM JIT compiler framework that is used for just-in-time generation of machine code. The first time you run a Julia function, it is parsed and the types are inferred. Then, LLVM code is generated by the JIT (just-in-time) compiler, which is then optimized and compiled down to native code. The second time you run a Julia function, the native code already generated is called. This is the reason why, the second time you call a function with arguments of a specific type, it takes much less time to run than the first time (keep this in mind when doing benchmarks of Julia code). This generated code can be inspected. Suppose, for example, we have defined a f(x) = 2x + 5 function in a REPL session. Julia responds with the message, f (generic function with 1 method); the code is dynamic because we didn't have to specify the type of x or f. Functions are by default generic because they are ready to work with different data types for their variables. The code_llvm function can be used to see the JIT bytecode, for example, the version where the x argument is of type Int64:

julia> code_llvm(f, (Int64,))

define i64 @"julia_f;1065"(i64) {
top:
  %1 = shl i64 %0, 1, !dbg !3248
  %2 = add i64 %1, 5, !dbg !3248
  ret i64 %2, !dbg !3248
}

The code_native function can be used to see the assembly code generated for the same type of x:

julia> code_native(f, (Int64,))
        .text
Filename: none
Source line: 1
        push    RBP
        mov     RBP, RSP
Source line: 1
        lea     RAX, QWORD PTR [RCX + RCX + 5]
        pop     RBP
        ret

Compare this with the code generated when x is of type Float64:

julia> code_native(f, (Float64,))
        .text
Filename: none
Source line: 1
        push    RBP
        mov     RBP, RSP
Source line: 1
        vaddsd  XMM0, XMM0, XMM0
        movabs  RAX, 48532256
        vaddsd  XMM0, XMM0, QWORD PTR [RAX]
        pop     RBP
        ret

Julia code is fast because it generates specialized versions of functions for each data type. Julia implements automatic memory management. The user doesn't have to worry about allocating and keeping track of the memory for specific objects. Automatic deletion of objects that are not needed any more (and hence, reclamation of the memory associated with those objects) is done using a garbage collector (GC). The garbage collector runs at the same time as your program. Exactly when a specific object is garbage collected is unpredictable. In Version 0.3, the GC is a simple mark-and-sweep garbage collector; this will change to an incremental mark-and-sweep GC in Version 0.4. You can start garbage collection yourself by calling gc(), or if it runs in the way you can disable it by calling gc_disable().

The standard library is implemented in Julia itself. The I/O functions rely on the libuv library for efficient, platform-independent I/O. The standard library is also contained in a package called Base, which is automatically imported when starting Julia.

 

Summary


By now, you should have been able to install Julia in a working environment you prefer. You should also have some experience with working in the REPL. We will put this to good use starting in the next chapter, where we will meet the basic data types in Julia, by testing out everything in the REPL.

About the Author
  • Ivo Balbaert

    Ivo Balbaert is a lecturer in web programming and databases at CVO Antwerpen, a community college in Belgium. He received a PhD in applied physics from the University of Antwerp in 1986. He worked for 20 years in the software industry as a developer and consultant in several companies, and for 10 years as project manager at the University Hospital of Antwerp. From 2000 onwards, he switched to partly teaching and partly developing software (at KHM Mechelen, CVO Antwerpen). He also wrote an introductory book in Dutch about developing in Ruby and Rails, Programmeren met Ruby en Rails, published by Van Duuren Media. In 2012, he authored a book on the Go programming language, The Way to Go, published by iUniverse. He has written a number of introductory books for new programming languages, notably Dart, Julia, Rust, and Red, all published by Packt.

    Browse publications by this author
Latest Reviews (19 reviews total)
The text of the document is not polished - could use more editorial care. It's also out of date with respect to the language definition found online, but I understand a new version is coming soon. However, it was enough to get me started in this new language.
インストールから基本文法まで網羅されている点が良かった。 PDFにもシンタックスハイライトがほしい。 図を描画するコマンドを集約したページやサンプルコードがほしい。
Quite instructive , it connects you with other languages thus is easy to follow.
Getting Started with Julia
Unlock this book and the full library FREE for 7 days
Start now