VC ++:std ::(w)ifstream表现不佳

时间:2014-07-25 07:05:16

标签: c# c++ windows io std

我有一个相当大的文本文件(大约5 000 000行,大约350 MB)。它是一个测试文件,因此所有行看起来都一样:

  

25.07.2014 1:00:22 | f2b5867b-51d2-4d06-b1a1-21bad529652c |测试消息

     

25.07.2014 1:00:22 | fe4fea0c-2ef7-4f34-b78c-fa561c826171 |测试消息

     

25.07.2014 1:00:22 | e6e11dc0-0ae8-40ac-9ab0-bd219636a5b2 |测试消息

我已经在C#和VC ++中编写了两个非常简单的应用程序,它们逐行读取并计算它们:

C#:

private static void Run()
{
    const string file = @"C:\Foo\Bar.txt";

    var stopwatch = new Stopwatch();
    stopwatch.Start();
    var lineCount = EnumerateLines(file).Count();
    Console.WriteLine(lineCount);
    stopwatch.Stop();
    Console.WriteLine(stopwatch.Elapsed);
}

private static IEnumerable<string> EnumerateLines(string file)
{
    using (var reader = new StreamReader(file))
    {
        while(reader.EndOfStream == false)
        {
            yield return reader.ReadLine();
        }
    }
}

C ++:

StopWatch stopwatch;
stopwatch.Start();
std::wifstream stream;
stream.open("C:\\Foo\\Bar.txt", std::ios_base::in);
DWORD lineCount = 0;
std::wstring line;
while (std::getline(stream, line))
{
    lineCount++;
}

stopwatch.Stop();
std::cout << lineCount << std::endl;
std::cout << stopwatch.GetElapsedTime() << std::endl;

这些程序做同样的事情,但性能却到处都是:

  • C# - ~1.7秒
  • C ++(使用wifstream和wstring) - 约39秒
  • C ++(使用ifstream和string) - ~5.5秒

所有应用程序都是使用&#39;发布&#39;配置。

你可以向我解释一下吗?为什么C#程序表现更好?为什么wifstream的表现比ifstream差得多?

提前致谢。

修改

我还尝试使用手动缓冲区大小:

const auto lineSize = 1024; // .NET's StreamReader bufferSize is 1024 by default
wchar_t line[lineSize];
while (stream.getline(line, lineSize))
{
    lineCount++;
}

这样性能好一点(wifstream约为37秒,ifstream约为4.1秒),但仍然非常慢。

0 个答案:

没有答案