为什么我的D代码对向量求和的速度比C慢?
我想知道为什么D代码这么慢?我最初使用std.algorithm.sum,但性能更差 我的D代码:为什么我的D代码对向量求和的速度比C慢?,d,D,我想知道为什么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];
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;
}
尝试使用gcc或ldc构建它。 dmd编译器是其他编译器应该使用的语言参考,但它不会生成特别快的二进制文件。
gcc要好得多。您可以从
std.array
使用uninitializedArray
提高速度,并直接使用foreach over array:
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);
}
您应该使用-release-inline-noboundscheck
参数
对于我来说,使用dmd的速度是否比使用ldmd2(ldc)或gdc的速度慢2倍,但是使用ldmd2(ldc)或gdc的速度与C版本的速度相同,您是否尝试过使用
foreach(int el;v){total+=el;}
,以及查看编译后的输出?C++完全可以将循环优化为仅<代码>总数=10000000;<代码>哇,这很有效,速度与我的C示例相同!我期待调查更多的D。我认为我的代码很慢,因为它隐式地初始化了“0”。@jimjampez,可能是循环中过度的边界检查
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);
}