为什么使用 ofstream 将 unsigned char* 写入二进制文件比预期慢?

问题描述

我创建了一个将无符号字符*数据保存到二进制文件函数。该进程在一个单独的线程中实现,并应该附加从队列(boost::lockfree::queue)接收到的数据。我的 SSD 驱动器理论上能够达到 ~5000MB/s 的写入速度,但我注意到它几乎从未超过 500MB/s。如果这很重要,我在 Windows 平台上。下面代码中的瓶颈可能是什么?

设置:相机输入 --> 图像采集板 --> 将数据写入内存 --> 使用 boost::lockfree::queue 排队数据 --> 按需弹出数据 --> 保存到二进制文件文件

void SaveData::saveAsBinary(std::string filePath,datafeed *d)
{
    saveThreadADone = false;    // std::atomic<bool> flag

    std::thread storeDataThread([this,filePath,d] {

    std::ofstream file = open(filePath,std::ios::beg | std::ofstream::out | std::ofstream::ate | std::ofstream::binary);
    if(outputFile.fail()){
        throw std::runtime_error("Cannot open file for saving.");
        }
   
        while(!d->isDataEmpty()) // Assume data collection is already done
        {           
            auto bufferData = d->getData().get(); // getData returns std::unique_ptr<unsigned char[]>
            size_t bufferDataSize = sizeof (bufferData);
            file.write(reinterpret_cast<char const*>(bufferData),bufferDataSize);
            if (!file.good())
            {
                throw std::runtime_error("There was an error while saving buffer data to file.");
            }
        }
        file.close();
        this->saveThreadADone = true;
    });

    storeDataThread.join();
}

std::unique_ptr<unsigned char[]> datafeed::getData()
{
    std::unique_ptr<unsigned char[]> output(nullptr);

    if(!dataQueue.empty()){ // boost::lockfree::queue<unsigned char*> dataQueue {100}
        dataQueue.pop(output);
    }
    return output;
}

bool datafeed::isDataEmpty()
{
    return dataQueue.empty();
}

// Somewhere else in the code
saveData_->saveAsBinary("specifiedpath",*datafeed);

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)