I am surprised by the results of this small performance test (Project Euler #1):
c: 233168 in 134 ms
java: 233168 in 46 ms
py: 233168 in 12 ms
I have attached the full code examples below as well as the execution shell script.
Does anyone have any idea as to why the c solution is so much slower than both the Java and Python solutions?
C
#include <stdio.h>
int main() {
int i, sum = 0;
for (i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
printf("%d\n", sum);
}
Java
class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
System.out.println(sum);
}
}
Python
total = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
total += i
print(total)
Run.sh - (slightly redacted for brevity)
milliseconds() {
gdate +%s%3N
}
exec_c() {
$build_cache/a.out
}
exec_py() {
python $build_cache/main.py
}
exec_java() {
java -classpath $build_cache Main
}
time_func() {
start_time=$(milliseconds)
output=$($1)
end_time=$(milliseconds)
delta_time=$((end_time - start_time))
echo "$output in $delta_time ms"
}
run() {
filename=$1
extension=${filename##*.}
case "$extension" in
"c")
cc $filename -o $build_cache/a.out
if [ $? -ne 0 ]; then
exit 1
fi
time_func exec_c
;;
"py")
cp $filename $build_cache/main.py
time_func exec_py
;;
"java")
javac -d $build_cache $filename 2>&1
if [ $? -ne 0 ]; then
exit 1
fi
time_func exec_java
;;
*)
echo "unsupported filetype"
exit 1
;;
esac
}