最近发现服务中有一个模块特别耗时,该模块负责读取一个 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
复制
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
复制
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
复制
每天一个开发小知识
文章转载自每天一个开发小知识,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。