【发布时间】:2022-06-11 02:03:00
【问题描述】:
我对这个小型性能测试(Project Euler #1)的结果感到惊讶:
c: 233168 in 134 ms
java: 233168 in 46 ms
py: 233168 in 12 ms
我已经附上了下面的完整代码示例以及执行 shell 脚本。
有没有人知道为什么 c 解决方案比 Java 和 Python 解决方案慢得多?
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
def multiples(end, start=1):
"""
Return all multiples of three and five between
the provided start and end integers.
"""
for i in range(start, end):
if i % 3 == 0 or i % 5 == 0:
yield i
# Sum of all real numbers between one and one-thousand.
total = sum(i for i in multiples(1000))
print(total)
Run.sh - (为简洁起见略有删节)
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
}
【问题讨论】:
-
这些测试太小了,没有任何意义,尤其是如果您只运行一次。
标签: python java c performance optimization