-–
title: “Why C is Faster than Python”
date: 2023-04-22T07:19:31+10:30
draft: True
Everybody knows: C is faster than Python.
But why is this? How can one language be faster than another? If the instructions tell the computer to do exactly the same thing, how can the run-time be different?
Let’s unpack this.
Here, I have c code that loops 100,000,000 times. On my computer, it runs in about 0.1 seconds.
#include <stdio.h>
#include <time.h>
int main()
{
int operation_count = 100000000;
struct timespec start_time, end_time;
clock_gettime(CLOCK_MONOTONIC, &start_time);
for (int i = 0; i < operation_count; i++)
{
;
};
clock_gettime(CLOCK_MONOTONIC, &end_time);
double secs_passed = (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_nsec - start_time.tv_nsec) / 1000000000.0;
printf("Time taken: %.2f seconds\n", secs_passed);
}
The equivalent, in Python, looks like this.
import time
start = time.time()
for i in range(100000000):
pass
end = time.time()
print(f"elapsed time: {end - start:.2f} seconds")
On my computer, this runs in about 2 seconds.
Why is this the case? How can there be about a 20x speed increase by using c? If this is the case, why aren’t all applications just written in c?