IDEの外部で実行していることを確認してください。それが鍵です。
-編集-私はSLaksのコメントが大好きです。「これらの回答の誤った情報の量は驚異的です。」:D
みんな落ち着いて。ほぼ全員が間違っていました。私は最適化を行いました。
私が行った最適化は十分ではなかったことがわかりました。
gettimeofdayを使用してGCCでコードを実行し(以下にコードを貼り付けます)、g++ -O2 file.cpp
C#よりもわずかに高速な結果を取得しました。
たぶんMSはこの特定のケースで必要な最適化を作成しませんでしたが、mingwをダウンロードしてインストールした後、私はテストされ、速度がほぼ同じであることがわかりました。
正義は正しいようです。PCで時計を使用することを誓い、それを使用してカウントしたところ、速度は遅くなりましたが、問題は解決しました。C ++の速度は、MSコンパイラではほぼ2倍遅くはありません。
私の友人がこれを私に知らせたとき、私はそれを信じることができませんでした。それで私は彼のコードを取り、それにいくつかのタイマーを置きました。
Booの代わりにC#を使用しました。私は常にC#でより速い結果を得ました。なんで?.NETバージョンは、使用した数に関係なく、ほぼ半分の時間でした。
C ++バージョン(悪いバージョン):
#include <iostream>
#include <stdio.h>
#include <intrin.h>
#include <windows.h>
using namespace std;
int fib(int n)
{
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
int main()
{
__int64 time = 0xFFFFFFFF;
while (1)
{
int n;
//cin >> n;
n = 41;
if (n < 0) break;
__int64 start = __rdtsc();
int res = fib(n);
__int64 end = __rdtsc();
cout << res << endl;
cout << (float)(end-start)/1000000<<endl;
break;
}
return 0;
}
C ++バージョン(より良いバージョン):
#include <iostream>
#include <stdio.h>
#include <intrin.h>
#include <windows.h>
using namespace std;
int fib(int n)
{
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
int main()
{
__int64 time = 0xFFFFFFFF;
while (1)
{
int n;
//cin >> n;
n = 41;
if (n < 0) break;
LARGE_INTEGER start, end, delta, freq;
::QueryPerformanceFrequency( &freq );
::QueryPerformanceCounter( &start );
int res = fib(n);
::QueryPerformanceCounter( &end );
delta.QuadPart = end.QuadPart - start.QuadPart;
cout << res << endl;
cout << ( delta.QuadPart * 1000 ) / freq.QuadPart <<endl;
break;
}
return 0;
}
C#バージョン:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
using System.IO;
using System.Diagnostics;
namespace fibCSTest
{
class Program
{
static int fib(int n)
{
if (n < 2)return n;
return fib(n - 1) + fib(n - 2);
}
static void Main(string[] args)
{
//var sw = new Stopwatch();
//var timer = new PAB.HiPerfTimer();
var timer = new Stopwatch();
while (true)
{
int n;
//cin >> n;
n = 41;
if (n < 0) break;
timer.Start();
int res = fib(n);
timer.Stop();
Console.WriteLine(res);
Console.WriteLine(timer.ElapsedMilliseconds);
break;
}
}
}
}
GCCバージョン:
#include <iostream>
#include <stdio.h>
#include <sys/time.h>
using namespace std;
int fib(int n)
{
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
int main()
{
timeval start, end;
while (1)
{
int n;
//cin >> n;
n = 41;
if (n < 0) break;
gettimeofday(&start, 0);
int res = fib(n);
gettimeofday(&end, 0);
int sec = end.tv_sec - start.tv_sec;
int usec = end.tv_usec - start.tv_usec;
cout << res << endl;
cout << sec << " " << usec <<endl;
break;
}
return 0;
}