C#でProject Euler(5) 速度

ここで時間計測をしてみましょう。

using System;
using System.Linq;

class e001 {
    static void Main(string[] args) {
        var sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        
        const int   N = (int)1e9;
        var s = Enumerable.Range(1, N - 1).
                        Where(n => n % 3 == 0 || n % 5 == 0).
                        Select(n => (long)n).Sum();
        Console.WriteLine(s);
        
        sw.Stop();
        Console.WriteLine(sw.Elapsed.ToString());
    }
}

出力は、

233333333166666668
00:00:16.6120255

約16.6秒ですね。ちなみに最適化をかけてもほぼ同じでした。
これを手続き型で書くと、

        var s = 0L;
        for(int n = 1; n < N; ++n) {
            if(n % 3 == 0 || n % 5 == 0)
                s += n;
        }
233333333166666668
00:00:02.7635495

C++で書くと、

#include <cstdio>
#include <windows.h>
#pragma comment(lib, "winmm.lib")

int main() {
    const int   t0 = timeGetTime();
    
    const int   N = (int)1e9;
    auto    s = 0LL;
    for(int n = 1; n < N; ++n) {
        if(n % 3 == 0 || n % 5 == 0)
            s += n;
    }
    printf("%lld\n", s);
    printf("%.3fsec\n", (timeGetTime() - t0) * 1e-3);
}
233333333166666668
1.797sec

1.5倍くらいですか。
Pythonなら、

from itertools import *
import time

t0 = time.clock()
N = 10 ** 9
print sum(n for n in xrange(1, N) if n % 3 == 0 or n % 5 == 0)
print time.clock() - t0
233333333166666668
131.488288563

同じコードでPyPyなら、

233333333166666668
40.2574341672

まとめると、

言語 実行時間
C++ 1.80s
C#(手続き型) 2.76s
C#(関数型) 16.6s
PyPy 40.3s
Python 131s

やっぱりC#を関数型で書くと遅いですね。ただ、もっと複雑なコードになってくるとこうはならないと思います。