一些示例代码。这是使用 cregex_iterator 的 c++11 部分:
std::chrono::steady_clock::time_point begin0 = std::chrono::steady_clock::now();
regex re("<option[\\s]value[\\s]*=[\\s]*\"([^\">]*)\"[\\s]*[^>]*>", regex::icase);
int found = 0;
for (std::cregex_iterator i = std::cregex_iterator(input, input + input_length, re);
i != std::cregex_iterator();
++i)
{
found++;
if (found < 10000) continue;
break;
}
std::chrono::steady_clock::time_point end0 = std::chrono::steady_clock::now();
这是PCR部分。正则表达式都是一样的。
std::chrono::steady_clock::time_point begin4 = std::chrono::steady_clock::now();
const char *pError = NULL;
int errOffset;
int options = PCRE_MULTILINE | PCRE_CASELESS;
const char* regexp = "<option[\\s]value[\\s]*=[\\s]*\"([^\">]*)\"[\\s]*[^>]*>";
pcre* pPcre = pcre_compile(regexp, options, &pError, &errOffset, 0);
int offset = 0;
int matches = -1;
int pMatches[6];
while (offset < input_length)
{
matches = pcre_exec(pPcre,NULL, input, input_length, offset,0, pMatches,6);
if (matches >= 1)
{
found++;
offset = pMatches[1];
if (found < 10000) continue;
break; // find match
}
else
offset = input_length;
}
std::chrono::steady_clock::time_point end4 = std::chrono::steady_clock::now();
结果表明 PCRE 比 C++11 快 100 倍。我在 c++11 实现中发现了一些向量复制和调整大小。还有其他原因吗?