我想知道为什么D代码这么慢?我最初使用std.algorithm.sum,但性能更差.
我的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);
}
Run Code Online (Sandbox Code Playgroud)
建造使用:
dmd -O arraysum.d
Run Code Online (Sandbox Code Playgroud)
等效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;
}
Run Code Online (Sandbox Code Playgroud)
内置:
clang -O3 -o csum arraysum.c
Run Code Online (Sandbox Code Playgroud)
您可以使用uninitializedArrayfrom 来提高速度std.array并直接使用foreach而不是数组:
import std.algorithm;
import std.stdio;
import std.array;
void main()
{
immutable int n = 10000000;
auto v = uninitializedArray!(int[])(n);
fill(v, 1);
int total = 0;
foreach (i; v) {
total += i;
}
writeln(total);
}
Run Code Online (Sandbox Code Playgroud)
你应该使用-release -inline -noboundscheck参数
对于我来说,使用dmd是2倍慢但是使用ldmd2(ldc)或gdc与C版本的速度相同