暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

411.耗时的 boost::lexical_cast

最近发现服务中有一个模块特别耗时,该模块负责读取一个 Json 数据,将其中指定字段存入 protobuf 结构中。


模块中含有大量的 try 和 boost::lexical_cast 代码。


    try
    {
        result_pb.id = boost::lexical_cast<unsigned long>(value["id"].asString());
    }
    catch (boost::bad_lexical_cast& e)
    {
        cout << "error:" << e.what() << endl;
    }
    复制


    为了验证是 try 耗时,还是 boost::lexical_cast 耗时,写了三段测试程序。


    atoi 耗时


      int in;
      uint64_t num = 300000000;
      string s = "1234567890";


      time_t begin = time(NULL);
      for (uint64_t i = 0; i < num; ++i)
      {
      in = atoi(s.c_str());
      if (0 == (i % 10000000))
      {
      cout << "atoi i:" << i << std::endl;
      }
      }
      cout << "atoi run time(s):" << to_string(time(NULL) - begin) << std::endl; // 9s
      复制


      boost::lexical_cast 耗时

        begin = time(NULL);
        for (uint64_t i = 0; i < num; ++i)
        {
        in = boost::lexical_cast<int>(s);
        if (0 == (i % 10000000))
        {
        cout << "lexical_cast i:" << i << std::endl;
        }
        }
        cout << "lexical_cast run time(s):" << to_string(time(NULL) - begin) << std::endl; // 16s
        复制

        try 耗时

          begin = time(NULL);
          for (uint64_t i = 0; i < num; ++i)
          {
          try
          {
          in = atoi(s.c_str());
          if (0 == (i % 10000000))
          {
          cout << "try i:" << i << std::endl;
          }
          }
          catch (boost::bad_lexical_cast & e)
          {
          cout << "i:" << to_string(i) << "e:" << e.what() << std::endl;
          }
          }
          cout << "atoi run time(s):" << to_string(time(NULL) - begin) << std::endl; // 9s
          复制

          可以发现,atoi 耗时 9s,boost::lexical_cast 耗时 16s,try 搭配 atoi 耗时 9s。

          所以,耗时的是 boost::lexical_cast,果断将模块中的 boost::lexical_cast 改成 atoi。

          每天一个开发小知识

          2022.5.24

          文章转载自每天一个开发小知识,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

          评论