Esse blog mudou para: http://gustavopaes.net/blog/
Python versus C: qual é mais rápido?
Para responder à pergunta, usei um código, que fiz inicialmente em Python, para resolver o problema 9 do Project Euler.
O resultado segue abaixo:
Python levou 66 segundos para retornar o resultado.
C levou 16 segundos para retornar o mesmo resultado.
Segue os códigos para comparação.
Código em Python
import time
limit = 1000
start = time.time()
for a in range(1, 500):
for b in range(1, 500):
for c in range(1, limit+1):
if (a**2 + b**2 == c**2) and (a+b+c==limit):
end = time.time()
print "%d + %d + %d = %d" % (a, b, c, limit)
print "Total time: %d" % (end-start)
exit()
Código em C
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main(int argc, char **argv)
{
time_t start, end;
int a, b, c, limit;
limit = 1000;
start = time(NULL);
for(a = 1; a < 500; a++)
{
for(b = 1; b < 500; b++)
{
for(c = 1; c < 500; c++)
{
if( (pow(a, 2) + pow(b, 2) == pow(c, 2)) && (a + b + c == limit) )
{
end = time(NULL);
printf("%d + %d + %d = %d\n\a", a, b, c, limit);
printf("Total time: %d\n\n", end-start);
system("pause");
return 0;
}
}
}
}
system("pause");
return 0;
}
Observação: O código em C foi compilado pelo DJGPP