今天在测试软件时发现使用纯VC软件刷新IO状态无明显延时, 但使用C#程序调用VC编写的动态库有较明显延时, 经测试发现出现延时的根本原因为: VS2015的VC动态库中使用C++11标准的正则表达式搜索数据算法, 使用替代方式后此问题解决。
使用C++标准库的正则表达式库, C#下调用时耗时为1至2秒(100个IO测试), VC下调用的耗时30至100毫秒左右。
修改前
string recvTxt(recvBuf);
regex pattern(R"(\[\d+,\d+,\d+,\d+\])");
cmatch cm;
struct {
UINT ch;
UINT diVal;
UINT diInvertFlag;
UINT doVal;
} didoInfo;
srcStr = recvBuf;
while (regex_search(srcStr, cm, pattern)) {
if (4 != sscanf_s(cm[0].str().c_str(), "[%d,%d,%d,%d]",
&didoInfo.ch, &didoInfo.diVal, &didoInfo.diInvertFlag, &didoInfo.doVal)) {
AddLogItem(ML_ERROR, 0, "接收DI DO状态[%s]格式错误!", cm.str().c_str());
} else {
int ch = didoInfo.ch;
ASSERT(ch >= 0);
if (s_DiStatus.size() <= ch) {
s_DiStatus.resize(ch + 1);
s_DoStatus.resize(ch + 1);
s_DiStatus[ch].channel = ch;
s_DoStatus[ch].channel = ch;
}
//DI状态
s_DiStatus[ch].value = didoInfo.diVal == (UINT)ON ? ON : OFF;
//DO状态
s_DoStatus[ch].value = didoInfo.doVal == (UINT)ON ? ON : OFF;
}
srcStr = cm.suffix().first;
}
修改后
struct {
UINT ch;
UINT diVal;
UINT diInvertFlag;
UINT doVal;
} didoInfo;
srcStr = recvBuf;
while (srcStr = strstr(srcStr, "[")) {
if (4 != sscanf_s(srcStr, "[%d,%d,%d,%d]",
&didoInfo.ch, &didoInfo.diVal, &didoInfo.diInvertFlag, &didoInfo.doVal)) {
AddLogItem(ML_ERROR, 0, "接收DI DO状态[%s]格式错误!", srcStr);
}
else {
int ch = didoInfo.ch;
ASSERT(ch >= 0);
if (s_DiStatus.size() <= ch) {
s_DiStatus.resize(ch + 1);
s_DoStatus.resize(ch + 1);
s_DiStatus[ch].channel = ch;
s_DoStatus[ch].channel = ch;
}
//DI状态
s_DiStatus[ch].value = didoInfo.diVal == (UINT)ON ? ON : OFF;
//DO状态
s_DoStatus[ch].value = didoInfo.doVal == (UINT)ON ? ON : OFF;
}
srcStr = strstr(srcStr, "]");
}