'Why is my Python code faster than my C code?
I recently began learning C, so as a performance test versus python I created the following code to loop through every possible 8 character alphanumeric combination. I noticed the python code ran roughly 20x faster than the C code despite the fact they were mostly the same code. I used PyCharm for the python code and CLion for the C code. Running the .exe file outside of CLion produced the same speed. Here is the code.
Python:
char_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for char1 in char_list:
for char2 in char_list:
for char3 in char_list:
for char4 in char_list:
for char5 in char_list:
for char6 in char_list:
for char7 in char_list:
for char8 in char_list:
print(char1 + char2 + char3 + char4 + char5 + char6 + char7 + char8)
C:
#include <stdio.h>
int main() {
char charset[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
for (int i1 = 0; i1 < sizeof charset; i1++) {
for (int i2 = 0; i2 < sizeof charset; i2++) {
for (int i3 = 0; i3 < sizeof charset; i3++) {
for (int i4 = 0; i4 < sizeof charset; i4++) {
for (int i5 = 0; i5 < sizeof charset; i5++) {
for (int i6 = 0; i6 < sizeof charset; i6++) {
for (int i7 = 0; i7 < sizeof charset; i7++) {
for (int i8 = 0; i8 < sizeof charset; i8++) {
printf("%c%c%c%c%c%c%c%c\n", charset[i1], charset[i2], charset[i3], charset[i4],
charset[i5], charset[i6], charset[i7], charset[i8]);
}
}
}
}
}
}
}
}
return 0;
}
Solution 1:[1]
Tried it myself, in a console, measuring the time for the first ten million lines:
Python:
$ time python3 main.py | head -10000000 | tail
...
real 0m6.075s
user 0m6.246s
sys 0m0.262s
C, compiled both ways mentioned in the first answer (now deleted):
$ gcc main.c -o main
$ time ./main | head -10000000 | tail
...
real 0m2.140s
user 0m2.350s
sys 0m0.300s
$ gcc -O3 -Ofast -Og -Os -funroll-loops -s main.c -o main
$ time ./main | head -10000000 | tail
...
real 0m2.119s
user 0m2.278s
sys 0m0.347s
My conclusion: Python isn't 20x faster at this but is slower, and what you observed is rather a slow speed of the consoles in which you ran the C program.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |