std::string get_raw_string(std::string const& s)
{
std::ostringstream out;
out << '\"';
out << std::hex;
for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
{
out << "\\x" << *it;
}
out << '\"';
return out.str();
}
out << std::hex << "\\x" << static_cast<int>(*it);
"\xffffffe4\xffffffb8\xffffffad" // get_raw_string("中")
typedef char int8_t;
std::string get_raw_string(std::string const& s)
{
std::ostringstream out;
out << '\"';
out << std::hex;
for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
{
// AND 0xFF will remove the leading "ff" in the output,
// So that we could get "\xab" instead of "\xffab"
out << "\\x" << (static_cast<short>(*it) & 0xff);
}
out << '\"';
return out.str();
}
template <typename OutputIterator>
bool generate_raw(OutputIterator sink, std::string s)
{
using boost::spirit::karma::hex;
using boost::spirit::karma::generate;
return generate(sink, '\"' << *("\\x" << hex) << '\"', s);
}
std::string get_raw_string_k(std::string const& s)
{
std::string result;
if (!generate_raw(std::back_inserter(result), s))
{
throw std::runtime_error("parse error");
}
return result;
}
// 输出格式为 "\x61\x62\x63",方便直接贴到 python 或 C++ 的代码中
'\"' << *("\\x" << hex) << '\"'
// 输出格式变为 "0x61 0x62 0x63 "
'\"' << *("0x" << hex << " ") << '\"'
#include "boost/test/unit_test.hpp"
#include "boost/../libs/spirit/optimization/measure.hpp"
#include "string.hpp" // The function for test
static std::string const message = "hex output performance test data 中文";
struct using_karma : test::base
{
void benchmark()
{
this->val += get_raw_string_c(message).size();
}
};
struct using_ostream : test::base
{
void benchmark()
{
this->val += get_raw_string(message).size();
}
};
BOOST_AUTO_TEST_CASE(TestStringPerformance)
{
BOOST_SPIRIT_TEST_BENCHMARK(
100,
(using_karma)
(using_ostream)
);
BOOST_CHECK_NE(0, live_code);
}
| 算法 | 耗时(s) |
| karma | 6.97 |
| ostream | 14.24 |
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有