#8: Introduction to IDEs + Debugging and Profiling

Part 1: IDEs

Context: Using IDEs

Throughout the missing semester sessions we have come across various command line tools such as the shell, editors, version control systems and containers. Knowing these from the command line is invaluable, especially on remote machines without a UI such as connection over SSH.

However, it is often more convenient to use these tools through a graphical interface. This is where IDEs (Integrated Development Environments) come in. IDEs are applications that combine a graphical text editor with interfaces to many of the tools we’ve already covered, such as git, compilers, build toolchains and debuggers which makes our lives as developers so much easier!

NOTE: These notes supplement the talk rather than replace it, as many of the IDEas (peak comedy) covered in this session will be shown via live demos. If you missed the talk, there are plenty of online guides for every VS Code feature (that probably also go much further in depth).

Editors vs. IDEs

Earlier in the course we looked at terminal editors like nano and Emacs (from previous sessions!):

Features an IDE gives you out of the box, which nano lacks and Emacs/Vim need plugins or configuration for:

The trade-off: nano and Emacs/Vim work anywhere over plain SSH and can usually be found to already be installed on alot of distributions (e.g. VI), while IDEs usually need extra setup for remote work and are alot larger in package size!

Much of this “language intelligence” comes from the Language Server Protocol (LSP): a “language server” (e.g. pyright for Python, clangd for C/C++, rust-analyzer for Rust) understands your code, and any editor that speaks LSP can use it, including VS Code, Emacs and Neovim. (Which is why many people can get away (or just prefer) using VIM / Emacs as replacement over standard IDEs)

IDEs in Industry

In most tech jobs you’ll spend much of your day in an IDE. Things you’ll likely come across:

Choice of IDE

What IDE you pick depends on the features you want, the language you use and your budget. Some are free and open source, some freeware, some paid (though JetBrains IDEs are free for us students).

For example, Python comes with IDLE, a barebones IDE that’s fine for beginners but lacks more powerful features. Python developers often move to JetBrains’ PyCharm, or a general-purpose IDE like VS Code.

Common alternative IDEs

Visual Studio Code

We will use VS Code in this session, since it is powerful, versatile and lightweight (and also my personal choice for longer tasks like writing these notes). It supports many languages out of the box and many more through its extensions marketplace. It even comes with “Chat”, an AI agent (opinions on that left as an exercise for the reader…). If you want fully open-source builds without Microsoft’s additions, try VSCodium.

It doesn’t really matter which IDE you use. Everything shown today (explorer, search, git, running code, breakpoints, stepping, inspecting variables etc) exists in practically every modern IDE with different buttons and shortcuts. Some IDEs are just better suited to certain languages (or just personal preference).

Demo - basic overview

Useful Windows/Hotkeys

On macOS, use cmd instead of ctrl.

Extensions

Out of the box, VS Code is closer to a smart text editor. Extensions are what turn it into a Python IDE, a C++ IDE, a LaTeX editor, and so on, usually by adding a language server and a debugger.

Finding the extensions you need

Useful Extensions

Security Notice

VS Code’s extensions are powerful but the marketplace is a community marketplace where anyone can upload code, and it doesn’t have to be open source, so you are effectively running others’ code blindly.

Some authors are verified (e.g. Microsoft’s official extensions), and ratings, age and download counts can help, but don’t rely on these alone. Attacks via extensions can and do occur, especially AI-themed ones!

Git Integration

The Source Control view (ctrl+shift+g) is a graphical front end to the same git commands from the version control lecture:

The GUI is great for reviewing diffs, but probably best to still know the commands too!

Demo - Running a Python file

  1. Install the Python extension (this also installs Pylance and the Python Debugger).
  2. Open a folder and create average.py.
  3. Check the selected interpreter in the bottom-right of the status bar (or run Python: Select Interpreter).
  4. Write the code:
def average(numbers):
    total = 0
    for i in range(1, len(numbers)):
        total += numbers[i]
    return total / len(numbers)

scores = [72, 85, 90, 64]
print(f"Average score: {average(scores)}")
  1. Click the “Run Python File” (play) button in the top-right. This just runs python3 average.py in the integrated terminal.
Average score: 59.75

But (72 + 85 + 90 + 64) / 4 is 77.75. Our program runs, but it’s wrong. Time to debug!


Part 2: Debugging

What is debugging?

A bug is any case where a program behaves differently to how we intended. It may crash, give the wrong answer or just hang.

Debugging is finding out why your program isn’t working and fixing it. The hard part is rarely the fix but rather finding where the program’s behaviour changes from what you expected. Debugging tools let you see what your program is actually doing, rather than what you think it’s doing.

(Fun fact: in 1947, Grace Hopper’s team found an actual moth in a relay of the Harvard Mark II and taped it into their logbook as the “first actual case of bug being found”. The joke was that engineers already called faults “bugs”.)

Debugging with Print Statements

One of the simplest methods to debug a program is to add print statements, printing values or logging that a certain point in the code has been reached.

Let’s take our previous broken python code:

def average(numbers):
    total = 0
    for i in range(1, len(numbers)):
        total += numbers[i]
        print(total)
    return total / len(numbers)

scores = [72, 85, 90, 64]
print(f"Average score: {average(scores)}")

Here the line print(total) has been added so we can keep track of the value of total. our output:

85
175
239
Average score: 59.75

From this our error is pretty clear! Total should start at 72, not 85. All we have to do is find what caused it to be 85 first, and we can see its because of i starting at 1.

There are downsides to this method however!

A debugger solves this: it lets you pause a running program, inspect its state, and step through it line by line, without modifying the code.

Debugging in VS Code

VS Code’s debugger drives a language-specific debugger underneath: debugpy for Python, and gdb or lldb for C/C++. So the VS Code debugger for C is literally driving the same gdb we’ll use in the shell later on.

Action Shortcut
Start / Continue F5
Step Over F10
Step Into F11
Step Out shift+F11
Stop shift+F5

For arguments, environment variables, or debugging tests/servers, create a .vscode/launch.json from the Run and Debug view.

Demo - debugging average.py

  1. Set a breakpoint on total += numbers[i] and press F5.
  2. In the Variables view, i is 1. Add numbers[i] to Watch: it’s 85, but the first score is 72!
  3. Press F5 a few times: i goes 1, 2, 3, never 0.
  4. Fix by ensuring i starts of as 0, and rerun to get the correct result.

Demo - debugging with the call stack

Here is the code of discountshopping.py

def apply_discount(price, discount_code):
    discounts = {"STUDENT": 0.10, "XMAS": 0.25}
    rate = discounts[discount_code]
    return price * (1 - rate)


def item_total(item):
    subtotal = item["price"] * item["quantity"]
    return apply_discount(subtotal, item["code"])


def order_total(order):
    total = 0
    for item in order:
        total += item_total(item)
    return total


basket = [
    {"name": "Keyboard", "price": 50, "quantity": 1, "code": "STUDENT"},
    {"name": "Mouse",    "price": 20, "quantity": 2, "code": "XMAS"},
    {"name": "Monitor",  "price": 150, "quantity": 1, "code": "xmas"},
]

print(f"Order total: {order_total(basket)}")

Running this file throws errors

total += item_total(item)
             ~~~~~~~~~~^^^^^^
  File "callstack.py", line 9, in item_total
    return apply_discount(subtotal, item["code"])
  File "callstack.py", line 3, in apply_discount
    rate = discounts[discount_code]

However, this does not make what the error is very obvious.

We could use the above methods such as breakpoints + variable watch, however as we have many functions being used, this may be too confusing / time consuming. Instead, we can view the call stack in the debugger.

Debugging outside the IDE: gdb

Sometimes you don’t have an IDE: you’re SSH’d into a server, or debugging a binary without its source. For C/C++ on Linux, the classic tool is gdb (the GNU Debugger), a powerful and free debugger that lets you explore and modify programs during runtime. Everything we just did in VS Code, you can do in gdb.

Intro and Setup

Debuggers like gdb use symbol tables in executables, which catalogue functions, variables and their scopes.

gdb can be installed with your package manager, e.g. apt install gdb (on macOS, use lldb, which works similarly).

Configuration can be stored in ~/.gdbinit. Useful settings include set disassembly-flavor intel (more readable assembly) and set print asm-demangle on (readable C++ function names). Plugins such as peda, gef and pwndbg are also loaded from here (see Plugins).

Debugging your own program

Compile with debug symbols (-g) and optimisation disabled (-O0):

g++ -g -O0 main.cpp -o main

Demos

Demo 1 - basic debugging

#include <iostream>
#include <stdlib.h> //srand
#include <stdio.h>  //printf

using namespace std;

int main () {

    srand (time(NULL));

    int alpha = rand() % 8;
    cout << "Hello world." << endl;
    int beta = 2;

    printf("alpha is set to is %s\n", alpha);
    printf("kiwi is set to is %s\n", beta);

    return 0;
}

We compile with g++ main.cpp -g -O0 -o main and run it. Sadly, we get a segmentation fault :(

Run gdb main to get a (gdb) prompt, then type run:

Program received signal SIGSEGV, Segmentation fault.
__strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:74
../sysdeps/x86_64/multiarch/strlen-avx2.S: No such file or directory.

We get the signal (SIGSEGV, a segmentation fault) and where it stopped, but that’s deep inside the C standard library, not our code. backtrace (or bt) shows the full chain of calls:

#0  __strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:74
#1  0x00007f59aee0ed31 in __vfprintf_internal (s=0x7f59aefb3780
<_IO_2_1_stdout_>, format=0x55ab53463011 "alpha is set to is %s\n",
    ap=ap@entry=0x7ffe8e60e700, mode_flags=mode_flags@entry=0) at
./stdio-common/vfprintf-internal.c:1517
#2  0x00007f59aedf879f in __printf (format=<optimized out>) at
./stdio-common/printf.c:33
#3  0x000055ab534622a4 in main () at main.cpp:15

Frame #3 shows the crash came from line 15 of main.cpp. There, %s expects a pointer to a string, but we passed an int, so printf reads from an invalid address. Changing %s to %d fixes it. This is the same as VS Code’s Call Stack view, in text form.

Demo 2 - changing values

gdb lets us inspect and change variables while the program runs:

#include <iostream>

using namespace std;

int main () {

    volatile int decider = 1;
    if (decider == 1){
        cout << "you lose" << endl;
    } else {
        cout << "you win" << endl;
    }

    return 0;
}

Break on main, run, and step over the assignment:

(gdb) b main
Breakpoint 1 at 0x1151: file main.cpp, line 7.
(gdb) r
Breakpoint 1, main () at main.cpp:7
7           volatile int decider = 1;
(gdb) s
8           if (decider == 1){
(gdb) print decider
$1 = 1

Ah! Panic! If decider is 1, we’ll lose! Let’s change that:

(gdb) set var decider = 2
(gdb) s
11              cout << "you win" << endl;

Printing variables

To print the values of all variables you can use:

info locals

or to print the value of one specific variable

print <variable name>
p <variable name>

Attaching gdb to running processes

Sometimes you may have processes running that might be bugging out, in which case you may want to use gdb instead of restarting the process to try replicate the error!

To attach gdb to a running process (elevated privileges may be required!)

gdp -p <pid>

or from within gdb

(gdb) attach <pid>

(Get pid by using the ps command which was covered in advanced shell!)

DEMO

#include <stdio.h>
#include <unistd.h>


int main () {
        int counter = 0;

        while (1) {
                counter++;
                printf("counter: %d\n", counter);
                sleep(1);
        }
        return 0;
}

This is a simple program that will increment a counter once per second.

Once attached, it’s helpful to run the bt or backtrace command.

bt
#0  0x00007f04b6e1fc5b in clock_nanosleep@GLIBC_2.2.5 () from /lib64/libc.so.6
#1  0x00007f04b6e2bf77 in nanosleep () from /lib64/libc.so.6
#2  0x00007f04b6e3e75e in sleep () from /lib64/libc.so.6
#3  0x0000000000401177 in main () at attachdemo.cpp:11

This shows the current call stack just like we did in VS code! From here we can see that our main function that we have attached to is #3, so to switch to it we can do:

frame 3

and we will now be “inside” our attached process and we can debug!

To detach:

detach

Plugins

gdb is even better with a plugin. Install one of these (they each add themselves to ~/.gdbinit and conflict with each other). They add a context view of registers, assembly and the stack, plus commands like checksec. As with VS Code extensions, stick to well-known projects.

peda:

$ git clone https://github.com/longld/peda.git ~/peda
$ echo "source ~/peda/peda.py" >> ~/.gdbinit

gef:

$ wget -O ~/.gdbinit-gef.py -q https://gef.blah.cat/py
$ echo source ~/.gdbinit-gef.py >> ~/.gdbinit

pwndbg:

$ git clone https://github.com/pwndbg/pwndbg
$ cd pwndbg
$ ./setup.sh

Part 3: A Little Bit of Profiling

So with debugging we can fix our broken code, but what if it’s running correctly but just taking a long time to run? (when realistically it shouldn’t) With profiling methods we can actually measure where all of our time is being spent!

Timing

The shell’s time command times a whole program:

$ time python3 profile_demo.py
real    0m0.71s
user    0m0.20s
sys     0m0.01s

real is wall-clock time; user and sys are CPU time in your code, user being time spent executing code in user mode, and sys being executing kernel code on behalf of your program. If real is much bigger than user + sys, your program is mostly waiting (on the network, disk, etc.), not computing.

This command can be really useful in actually benchmarking any optimisations you make! (The goal is to make time go down)

Easy to see the difference when running a command like:

time sleep 3

real: ~ 3 seconds because thats how long the program should run for.

user: Almost 0 because CPU did no meaningful computations.

sys: Also almost 0 because very little kernel processing would be needed.

Profilers

A profiler tells you where the time goes. Python ships with cProfile:

import time

def fetch_data():
    time.sleep(0.5)          # pretend this is a slow network call
    return list(range(1000))

def slow_sum(n):
    total = 0
    for i in range(n):
        total += i
    return total

def fast_sum(n):
    return n * (n - 1) // 2

def main():
    data = fetch_data()
    print(slow_sum(5_000_000))
    print(fast_sum(5_000_000))

main()
$ python3 -m cProfile -s cumtime profile_demo.py
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.697    0.697 profile_demo.py:16(main)
        1    0.000    0.000    0.500    0.500 profile_demo.py:3(fetch_data)
        1    0.500    0.500    0.500    0.500 {built-in method time.sleep}
        1    0.197    0.197    0.197    0.197 profile_demo.py:7(slow_sum)
        1    0.000    0.000    0.000    0.000 profile_demo.py:13(fast_sum)

tottime is time in the function itself; cumtime includes everything it calls. Most of the time is spent waiting in fetch_data, and slow_sum takes ~0.2s while fast_sum computes the same answer instantly.

You should also notice that the cumtime of main is the sum of time taken for fetch data + slow_sum!

Other tools worth knowing:


Conclusion

IDEs are a personal choice: you may like a heavier, full-featured IDE, or a lightweight one that stays out of your way, and you might use one for everything or switch per project. Play around, find what works for you, and find your productivity spike! (Hopefully. Missing Semester makes no guarantees of an improvement in productivity.)

Whatever you use, the debugging and profiling concepts are the same everywhere: breakpoints, stepping, inspecting state, call stacks, and measuring before optimising. Learn them once, and you can use gdb, pdb, or any other debugger you come across.


Edit this page.

Licensed under CC BY-NC-SA.