I am trying to replace an old piece of code which matches if substring is there in end of string with boost spirit. When i benchmark both implementation i see old implementation does it faster.
My questions are
- Is it wise to expect i would get faster parsing and matching when i replace old code with boost spirit.
- If (1.) is yes some suggestions on what i am doing wrong or what i shud do try.
logic explanation: if substring is "TRINNDECK" i need to check the last entry in "SERVERTRINN-11/TRINNDECK-1/TRINNUSER-1" has substring. all entries have simillar format (STRING-INT/STRING-INT) so in my example "SERVERMAGNUS-1/MAGNUSDECK-1/TRINNDECK-1" matches but not "SERVERTRINN-11/TRINNDECK-1/TRINNUSER-1"
#include <iostream>
#include <chrono>
#include <boost/spirit/home/x3.hpp>
bool isSubStrInStr(const std::string subStr, const std::string& str)
{
auto begin = str.find_last_of('/');
auto end = str.find_last_of('-');
if (end != std::string::npos)
{
if (begin != std::string::npos)
{
if (str.substr((begin + 1), (end - begin - 1)) == subStr)
{
return true;
}
}
else
{
if (str.substr(0, end) == subStr)
{
return true;
}
}
}
return false;
}
bool isSubStrInStrSpirit(const std::string& subStr, const std::string& str)
{
std::vector<std::string> values;
bool const result = boost::spirit::x3::parse(
str.begin(), str.end(),
+boost::spirit::x3::alnum % +(boost::spirit::x3::char_('-') >> boost::spirit::x3::int_ >> "/"),
values
);
if (result && values.back() == subStr)
{
return true;
}
return false;
}
int main()
{
std::string name = "TRINNDECK";
std::vector<std::string> infoMaps{
"SERVERTRINN-11/TRINNDECK-1/TRINNUSER-1",
"SERVERMAGNUS-1/MAGNUSDECK-1/TRINNDECK-1",
};
std::cout << "WITH SPIRIT" << std::endl;
auto start = std::chrono::steady_clock::now();
for (auto& item : infoMaps)
{
std::cout << item << " " << std::boolalpha << isSubStrInStrSpirit(name, item) << std::endl;
}
auto stop = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
std::cout << "Time taken: " << duration.count() << " microseconds." << std::endl;
std::cout << "WITHOUT SPIRIT" << std::endl;
start = std::chrono::steady_clock::now();
for (auto& item : infoMaps)
{
std::cout << item << " " << std::boolalpha << isSubStrInStr(name, item) << std::endl;
}
stop = std::chrono::steady_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
std::cout << "Time taken: " << duration.count() << " microseconds." << std::endl;
return 0;
}