---
title: Comparing MicroPython and C
heading: Speed, size, timing, and the time it takes to write
eyebrow: C12 · Lesson 49 · Comparing MicroPython and C
xp: 40
---

::: hook
This course has written every kind of program twice. The differences are now concrete: C toggles a pin in under a microsecond, MicroPython in 40; a C program for a small job is a hundred bytes, while MicroPython needs its whole interpreter on the chip before the first line runs; C's interrupt handlers respond in half a microsecond, MicroPython's soft ones whenever the interpreter next looks. Against that, MicroPython programs are shorter, easier to change while the board runs, and much more forgiving to write. Choosing between them, or using both, is an engineering decision with numbers behind it.
:::

::: play
- The same job in both languages: toggle a pin 100 times and print how long it took, measured by the board's own clock. The C version prints 705 cycles, 70 µs.
- The MicroPython version, below, prints 4000 µs: 57 times longer, nearly all of it the 40 µs each call into the hardware costs.
- Open the C version's compiled program: the whole thing is 27 instructions, 108 bytes.
:::
:::

```sim board
lang: c
attach: led P0
run: 10 ms
show: asm
code:
#include "board.h"

int main(void) {
    GPIO_DIR = 1;
    uint32_t start = SYS_CYCLES;
    for (int i = 0; i < 100; i++)
        GPIO_TOGGLE = 1;
    uint32_t cycles = SYS_CYCLES - start;
    print(cycles);            // clock cycles for 100 toggles
    print(cycles / 10);       // microseconds
    return 0;
}
```

```sim board
lang: micropython
attach: led P0
run: 0.1 s
code:
from machine import Pin
import time

led = Pin(0, Pin.OUT)
start = time.ticks_us()
for i in range(100):
    led.toggle()
print(time.ticks_diff(time.ticks_us(), start))   # microseconds
```

::: predict
## A job makes 2000 hardware calls. Roughly how long does it take in MicroPython on this board, and in C at about 7 cycles per call?

- [x] 80 ms and 1.4 ms
- [ ] 8 ms and 1.4 ms
- [ ] 80 ms and 14 ms
- [ ] The same, since both talk to the same hardware

::: reveal
80 ms in MicroPython ($2000 \times 40$ µs) and 1.4 ms in C ($2000 \times 7 \times 0.1$ µs). The hardware is the same; the difference is the work around each access: MicroPython looks up the method, checks the arguments' types and converts the values on every call, while C's compiled code is just a store.
:::
:::

::: nameit
## Speed

Each MicroPython operation goes through the interpreter: look up names, check types, allocate objects. On this board a hardware call costs about 40 µs; on real chips plain Python arithmetic also takes a few microseconds per operation, typically 10 to 100 times slower than C. (This course's board charges MicroPython time only for hardware calls and sleeps, so pure arithmetic looks free here; on a real chip it isn't.)

## Size and memory

A C program contains only what it uses: a hundred bytes for a blinker, a few kilobytes for most jobs. MicroPython needs its interpreter in flash, at least about 256 KB, and about 16 KB of RAM at minimum, before any user code; Python objects then take more RAM than C's packed data. Small, cheap microcontrollers can run C but not MicroPython.

## Timing

C code runs at a fixed speed, and its interrupts respond within a few cycles. MicroPython's speed varies with what the interpreter is doing; its **garbage collector** occasionally pauses to free memory; and its usual interrupts are **soft**, run between bytecodes. MicroPython can't give microsecond guarantees.

## Writing it

MicroPython wins on the time it takes to write and change a program: no compile step, a prompt to try things on the live board, floats, strings and lists that just work, and errors reported with a line number instead of a crash.

## Choosing, or mixing

| Use C for | Use MicroPython for |
|---|---|
| tight timing, fast interrupts | prototypes and experiments |
| small or cheap chips | logic that changes often |
| low power, battery life | text, data handling, user interfaces |
| drivers and signal processing | glue between finished components |

Many products mix them: C for the drivers and time-critical parts, exposed to MicroPython as a module, with the application written in Python on top.
:::

::: example
## A sensor logger reads 5 registers and writes 10 bytes over the UART every second, and sleeps the rest of the time. How much awake time does each version need?

::: solution
1. **Count the calls.** About 15 hardware calls.
2. **MicroPython.**
   $$15 \times 40\ \mu\text{s} = 0.6\ \text{ms}$$
   plus 0.9 ms for the UART bytes at 115,200 baud.
3. **C.** About 0.01 ms, plus the same 0.9 ms.
4. **Compare.** Both are asleep more than 99.8% of the time, so here the language barely matters to the battery: the UART's time dominates.

**Answer:** MicroPython needs 0.6 ms for the calls and C about 0.01 ms, plus 0.9 ms for the UART bytes either way.
:::
:::

::: example
## A motor commutation interrupt must respond within 2 µs. Which language?

::: solution
1. **C.** Its handler starts within a microsecond on this board.
2. **MicroPython.** Its soft interrupts run only when the interpreter reaches a safe point, tens of microseconds or more later.
3. **Garbage collection.** A collection can delay them by milliseconds.

**Answer:** C, whose handler starts within a microsecond.
:::
:::

::: example
## Reading 1000 ADC samples takes one hardware call per sample. About how long does it take in MicroPython at 40 µs a call, and in C at about 10 instructions a sample?

::: solution
1. **MicroPython.**
   $$1000 \times 40\ \mu\text{s} = 40\ \text{ms}$$
2. **C.**
   $$1000 \times 10 \times 100\ \text{ns} = 1\ \text{ms}$$
   about 40 times faster.
3. **Does it matter?** If the job happens once a second, either is fine; at 1000 times a second only C keeps up.

**Answer:** about 40 ms in MicroPython and 1 ms in C.
:::
:::

::: check
given: n = 100 | 1000 | 5000
answer: n*0.04
unit: ms
tolerance: 0.5%

## A MicroPython job makes {n} hardware calls at 40 µs each. How long do they take?

::: right
Right. {answer} ms.
:::

::: misses
- [any] Not yet. Calls times 40 µs.
:::
:::

::: check
given: n = 100 | 1000 | 5000; k = 5 | 7 | 10
answer: n*k*0.1/1000
unit: ms
tolerance: 0.5%

## A C loop makes {n} hardware accesses at {k} cycles each, at 10 MHz. How long do they take?

::: right
Right. {answer} ms.
:::

::: misses
- [any] Not yet. Accesses × cycles × 100 ns.
:::
:::

::: check
given: k = 5 | 7 | 10
answer: 40/(k*0.1)
tolerance: 0.5%

## A hardware access takes 40 µs in MicroPython and {k} cycles (100 ns each) in C. How many times faster is C?

::: right
Right. {answer} times.
:::

::: misses
- [any] Not yet. 40 µs over {k} × 0.1 µs.
:::
:::

::: check
given: F = 128 | 256 | 512 | 1024
answer: F - 256
unit: KB
tolerance: 0

## A chip has {F} KB of flash, and the MicroPython interpreter needs 256 KB. How much flash is left for everything else (negative if it doesn't fit)?

::: right
Right. {answer} KB.
:::

::: misses
- [any] Not yet. Flash minus the interpreter.
:::
:::

::: check
given: Ia = 2; t1 = 0.5 | 5; t2 = 0.05 | 0.2; f = 1 | 10
answer: Ia*(t1 - t2)*f/1000
unit: mA
tolerance: 0.5%

## A job runs {f} times a second, awake {t1} ms per run in MicroPython or {t2} ms in C, at {Ia} mA awake. How much more average current does the MicroPython version draw (sleep current aside)?

::: right
Right. {answer} mA.
:::

::: misses
- [any] Not yet. The extra awake time per second, times the awake current.
:::
:::

::: check
kind: choice

## Which job is the best fit for MicroPython?

- [ ] A 50 kHz motor control loop
- [ ] Firmware for a chip with 32 KB of flash
- [x] A test fixture that steps through settings and logs readings to a computer
- [ ] A 1 µs-latency safety shutdown interrupt

::: misses
- [1] 20 µs per loop is less than one MicroPython hardware call.
- [2] The interpreter alone needs far more.
- [4] Soft interrupts can't promise that.
:::
:::

::: check
kind: c
attach: led P0
run: 0.01
expect: edges(P0) = 1000; cycles < 9000

## Toggle P0 1000 times as fast as you can in C, then return.

```c starter
#include "board.h"

void wait(void) { for (volatile int i = 0; i < 10; i++) ; }

int main(void) {
    GPIO_DIR = 1;
    for (int i = 0; i < 1000; i++) {
        GPIO_TOGGLE = 1;
        wait();
    }
    return 0;
}
```

```c solution
#include "board.h"

int main(void) {
    GPIO_DIR = 1;
    for (int i = 0; i < 1000; i++)
        GPIO_TOGGLE = 1;
    return 0;
}
```

::: right
Right: about 7 cycles a toggle, 0.7 ms for all 1000. MicroPython would take 40 ms.
:::
:::

::: check
kind: micropython
attach: led P0
run: 0.2
expect: print = 2000

## Measure, with `time.ticks_us()`, how long 50 toggles of P0 take in MicroPython, and print it.

```micropython starter
from machine import Pin

led = Pin(0, Pin.OUT)
for i in range(50):
    led.toggle()
```

```micropython solution
from machine import Pin
import time

led = Pin(0, Pin.OUT)
start = time.ticks_us()
for i in range(50):
    led.toggle()
print(time.ticks_diff(time.ticks_us(), start))
```

::: right
Right: 50 × 40 µs.
:::
:::

::: check
kind: parts
given: n = 100 | 1000 | 10000; k = 10 | 30

## A job makes {n} hardware calls: about 40 µs each in MicroPython, or {k} instructions each in C on the 10 MHz board.

::: part
answer: n*0.04
unit: ms
tolerance: 0.5%

### How long does it take in MicroPython?

::: misses
- [any] Calls × 40 µs.
:::
:::

::: part
answer: n*0.04/(n*k*1e-4)
tolerance: 0.5%

### How many times faster is the C version?

::: misses
- [any] 40 µs over {k} × 0.1 µs.
:::
:::
:::

::: check
kind: parts
given: r = 2 | 10 | 100; a = 1 | 5

## A sensor job runs {r} times a second and takes {a} ms in MicroPython.

::: part
answer: r*a/10
unit: %
tolerance: 0.5%

### What share of the time is MicroPython busy?

::: misses
- [any] Rate × duration.
:::
:::

::: part
answer: step(1000/r - a)
tolerance: 0

### Does it fit at all (1 for yes)?

::: misses
- [any] Each run must finish before the next.
:::
:::
:::

::: explain
## Why do many products use C for drivers and timing-critical code but MicroPython (or another high-level language) for the application on top?

::: model
The two parts have different needs. Drivers and interrupt handlers run often, touch the hardware constantly and must meet microsecond deadlines, where C's speed and predictable timing are essential and its difficulty is worth paying once. The application logic (menus, data handling, protocols, configuration) changes far more often, runs less often, and is where most bugs and most of the development time go, so a language that's quicker to write, safer and easier to change saves the most there. Wrapping the C drivers as a module the high-level code calls gets each advantage where it counts, as long as the chip has room for the interpreter.
:::
:::

::: practice

::: check
given: n = 100 | 250 | 500 | 1000 | 2500 | 10000
answer: n*0.04
unit: ms
tolerance: 0.5%

## Time for {n} MicroPython hardware calls?

::: misses
- [any] n × 40 µs.
:::
:::

::: check
given: n = 300 | 8000; k = 6 | 8
answer: n*k*0.1/1000
unit: ms
tolerance: 0.5%

## Time for {n} C accesses at {k} cycles?

::: misses
- [any] n × k × 0.1 µs.
:::
:::

::: check
given: k = 2 | 3 | 4 | 5 | 6 | 8 | 10
answer: 40/(k*0.1)
tolerance: 0.5%

## Speedup of C at {k} cycles per access over 40 µs?

::: misses
- [any] 40 / (k × 0.1).
:::
:::
:::
