我想知道爲什麼D代碼太慢?我最初使用std.algorithm.sum,但性能更差。爲什麼我的D代碼將一個矢量加起來比C慢?
我d代碼:
import std.algorithm;
import std.stdio;
void main()
{
immutable int n = 10000000;
int[] v = new int[n];
fill(v,1);
int total = 0;
foreach (int i; 0 .. n) {
total += v[i];
}
writeln(total);
}
使用內置:
dmd -O arraysum.d
等效的C代碼:
#include <stdio.h>
#include <stdlib.h>
int main()
{
const int n = 10000000;
int *v = malloc(n * sizeof(int));
for (int i = 0; i < n; ++i) {
v[i] = 1;
}
int total = 0;
for (int i = 0; i < n; ++i) {
total += v[i];
}
printf("%d\n", total);
free(v);
return 0;
}
內置有:
並且您是否嘗試過'foreach(int el; v){total + = el;}',您是否也查看過編譯後的輸出? C++完全有可能將循環優化爲「total = 10000000;' – 2015-02-24 10:42:06