我正在通过串口实现一些基本通信。
根据协议,我必须在收到请求后的225ms内回答。最大包装尺寸为256B。
因此,当我收到请求时,我创建了响应[header, lenght, payload, crc16]
(总共256 B),平均需要30到40毫秒。然后,当我将响应(字节数组)放在asio::async_write
中时,会发生实际问题。该函数平均需要大约240ms才能处理该字节数组。
除非我发送最大长度的包裹,否则一切正常。它需要240ms(asio::async_write
)+ 40ms(封装组件)大约280~300 ms。
端口:9600波特,长度8,一个停止位
任何想法如何加快速度?
void Example::do_write()
{
if (pimpl_->WriteBuffer == nullptr)
{
boost::lock_guard<boost::mutex> l(pimpl_->WriteQueueMutex);
pimpl_->WriteBufferSize = pimpl_->WriteQueue.size();
pimpl_->WriteBuffer.reset(new byte[pimpl_->WriteQueue.size()]);
std::move(pimpl_->WriteQueue.begin(), pimpl_->WriteQueue.end(), pimpl_->WriteBuffer.get());
pimpl_->WriteQueue.clear();
begin = boost::chrono::steady_clock::now();
async_write(pimpl_->Port, asio::buffer(pimpl_->WriteBuffer.get(), pimpl_->WriteBufferSize), boost::bind(&Example::write_end, this, asio::placeholders::error));
}
}
void Example::write_end(const system::error_code& error)
{
if (!error)
{
boost::lock_guard<boost::mutex> l(pimpl_->WriteQueueMutex);
if (pimpl_->WriteQueue.empty())
{
pimpl_->WriteBuffer.reset();
pimpl_->WriteBufferSize = 0;
end = boost::chrono::steady_clock::now();
OutputDebugString(string("\nWRITE TIME: " + to_string(boost::chrono::duration_cast<boost::chrono::milliseconds>(end - begin).count()) + "\n").c_str());
return;
}
pimpl_->WriteBufferSize = pimpl_->WriteQueue.size();
pimpl_->WriteBuffer.reset(new byte[pimpl_->WriteQueue.size()]);
std::move(pimpl_->WriteQueue.begin(), pimpl_->WriteQueue.end(), pimpl_->WriteBuffer.get());
pimpl_->WriteQueue.clear();
async_write(pimpl_->Port, asio::buffer(pimpl_->WriteBuffer.get(), pimpl_->WriteBufferSize), boost::bind(&Example::write_end, this, asio::placeholders::error));
}
else
{
set_error_status(true);
do_close();
}
}
答案 0 :(得分:1)
根据我的经验,boost :: asio本身需要几微秒。您使用40 ms来获取数据,通信需要220 ms(在9600波特率下发送256个字节的最小值),在某处您浪费的时间更长20-40 ms,总和为280 - 300 ms。
怎么办?