[英]Why is there a huge difference in performance between the C++ Debug version and the Release version, but not C#?
在一些大型的C++項目中,Debug版本幾乎沒用,比如一些游戲引擎UnrealEngine、Ogre3d等,因為Debug版本的程序太卡運行,幾乎無法使用。 但是當我在開發一個C#程序的時候,我驚訝的發現C#應用程序的Debug版和Release版在體驗上的差異並沒有太大,以至於無法區分debug和release。 為什么?
// test C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApp21
{
internal class Program
{
static void DoSomething()
{
StringBuilder builder = new StringBuilder();
for(int i=0;i<10000000; ++i)
{
builder.Append(i.ToString());
}
Console.WriteLine($"{builder.ToString().Length}");
}
static void Main(string[] args)
{
#if DEBUG
Console.WriteLine("DEBUG:");
#else
Console.WriteLine("Release:");
#endif
Stopwatch sw = Stopwatch.StartNew();
DoSomething();
Console.WriteLine(sw.Elapsed.ToString());
}
}
}
調試:68888890 00:00:00.9831842
發布:68888890 00:00:00.8958183
// test cpp code
#include <iostream>
#include <string>
#include <boost/progress.hpp>
void DoSomething()
{
std::string str;
char buf[64];
for (int i = 0; i < 1000000; ++i)
{
sprintf_s(buf, "%d", i);
str.append(buf);
}
std::cout << str.size() << std::endl;
}
int main()
{
#ifdef _DEBUG
printf_s("DEBUG:");
#else
printf_s("RELEASE:");
#endif
boost::progress_timer timer;
DoSomething();
}
調試:5888890 0.33 秒
發布:5888890 0.06 秒
一個原因是c++可以優化更多。 由於所有工作都是提前完成的,因此它可以花費盡可能多的時間來找出轉換代碼的最佳方式。 .Net 由即時編譯器(jitter)編譯,因此需要快速編譯代碼,因此沒有時間進行任何昂貴的優化。 較新的.Net 版本支持分層編譯,因此可以對常用代碼進行更多優化。
由於 c# 和 .Net 比 c++ 以性能為中心的心態更注重確保正確性和開發人員的生產力,因此可以應用的優化也可能存在限制。
請注意,將調試器附加到 .Net 代碼將禁用某些類型的優化,因此在進行任何比較時需要小心。 您還需要小心 c++ 代碼,因為如果存在一些未定義的行為,一些更高級別的優化可能會導致編譯器僅刪除整個代碼部分。 還要檢查 c++ 代碼是否使用高精度計時器,而不是計算機時鍾。 如果名為“進步”的東西使用后者,我不會感到驚訝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.