SpazzOut for Python vs C on Raspberry Pi B+

The python is a fierce predator in the animal kingdom, but when it comes to computer languages, C is hard to beat for speed. If you are just getting started into programming, Python can be an easy language to learn, but if you have been programing long, you have probably heard programs coded in C will run faster than higher level languages. How much faster?  Read on to find out.

 

Python vs C Benchmark Test Hardware ConfigurationThis is how we had the Ranspberry Pi set up to measure the GPIO toggle frequency.

To compare these two programming languages a Raspberry Pi B+ was connected to a simple LED and resistor circuit via Pin 12 of Port 1 aka GPIO Pin 18 of the Broadcom BCM2835 used on the RPi. An oscilloscope was then placed across the circuit so that the period of the signal through the circuit could be measured.

 

Next, two programs were written to toggle the circuit on and off. One program was written in Python and the other was written in C. The source for each of these programs is given below.

 

Toggle GPIO Source Code in Python

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

while True:
    GPIO.output(18, True)
    GPIO.output(18, False)

Toggle GPIO Source Code in C

#include <bcm2835.h>

#define PIN18 RPI_GPIO_P1_12

int main(int argc, char **argv){
	if(!bcm2835_init())return 1; /* Initialize */
	bcm2835_gpio_fsel(PIN18, BCM2835_GPIO_FSEL_OUTP); /*Sets PIN18 to output*/
	
	while(1){					 /* Forever loop */
		bcm2835_gpio_set(PIN18); /* PIN18 = high */
		bcm2835_gpio_clr(PIN18); /* PIN18 = low  */
	}
}

Python Results

C Results

The Python program toggled the GPIO of the Raspberry Pi B+ at 59.5 Hz.
This scope plot shows how fast the GPIO of the Raspberry Pi B+ can be toggled when programming in C.

How Much Faster is C than Python?

Check out the time scale in the scope plots above. The Python results are measured in microseconds while the C results are measured in nanoseconds. Wowzers! That's SpazzTastic! The Python toggle takes 0.0000168 seconds (16.8 microseconds). That's 59.5 kHz. The C toggle takes 0.000000152 seconds (152 nanoseconds). That's 6.58 MHz! That makes the C program 110 times faster than Python!

 

Does that mean C is 110 time better than Python? Not quite. One advantage the Python program has is there is less code to write. Even though we are using the bcm2835.h library to provide a layer of abstraction for the C program, and make it easier to code, the Python program still beats the C program in having fewer lines of code.

 

Home | Products | Electronics | Programming | SpazzOuts | Contact
© Copyright 2014 - 2017 SpazzTech LLC. All Rights Reserved
Made with Adobe Muse