在VS 2012中,std :: istream提取运算符(double或float)非常慢

时间:2013-09-19 13:22:53

标签: c++ visual-studio-2008 visual-studio-2012 istream

我从VS2008迁移到VS2012,我发现VS2012版本的性能非常慢。

问题出在输入流的提取运算符中。 istream的&安培;运营商GT;> (float& val); istream的&安培;运营商GT;> (double& val);

VS2012上的文本文件上的这些功能慢两倍。

例如,以下代码检索VS2012的3.75 seconde和VS2008的1.25 seconde。

你能告诉我为什么吗?

提前感谢。

#include "stdafx.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <sstream>

#define FILE_NAME "D:\\test_Roadmap.txt"

const int NB_VALUE = 1000000;
const int NB_MESURE = 20;

int _tmain(int argc, _TCHAR* argv[])
{
  std::cout<<"ecriture"<<std::endl;
  //ecriture
  {
    std::ofstream ostream (FILE_NAME);
    float val = 0.f;

    for (int ii=0; ii<NB_VALUE; ii++)
    {
      ostream << val;
      ostream << " ";
      val += 0.04f;
    }

  }

  std::cout<<"lecture"<<std::endl;
  //lecture
  double texec = 0;
  for (int iMesure=0; iMesure<NB_MESURE; iMesure++)
  {
    std::ifstream istream (FILE_NAME);
    float val = 0;

    time_t tbegin1 = time(NULL);

    for (int ii=0; ii<NB_VALUE; ii++)
    {
      istream>> val;
    }

    time_t tbegin2 = time(NULL);

    texec += difftime(tbegin2,tbegin1);   

  }
  texec /= NB_MESURE;

  std::ostringstream oss1;
  oss1 << texec;
  std::string s1 = std::string(" read : ") + oss1.str() + std::string(" in s");
  std::cout<<s1<<std::endl;

  float a;
  std::cin>>a;

  return 0;
}

1 个答案:

答案 0 :(得分:1)

下面的链接指出了提取运算符&#34;从流中顺序提取和解析字符,将它们解释为正确类型值的表示。&#34;

http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

所以我认为在VS2012中实现提取运算符浮点数或双值非常慢,因为它依次解析并将字符解释为数字。最近,我在VS2012中遇到了同样的问题,而代码在VS2010编译中的运行速度提高了7倍。我能够通过使用提取算子&#34;&gt;&gt;&#34;来解决这个问题。用char []而不是double或float,然后使用atof()来获取double值。

以下是适合我的代码段

char inStr[64];
float val = 0;

std::ifstream istream (FILE_NAME);

istream >> inStr;
val = atof(inStr);