3

高级概述是,对于每个单独的整数数据值(第 9 行)和第 12 行,我在其中将逗号写入文件,都会调用“CFile 文件”的“file.write()”方法。

这意味着对于 327,680 个输入数据整数,有 2*327,680 = 655,360 次 file.write() 调用。由于这个原因,代码非常慢,因此,代码需要 3 秒来创建一个 csv 文件。如何提高代码的效率?

注意:我不能更改代码的任何声明。我必须使用 CFile。此外,pSrc 的类型为 uint_16_t,并且包含我要存储在 .csv 文件中的数据。数据范围为 0 - 3000 个整数值。

1           CFile file;
2           int mWidth = 512;
3           int mHeight = 640;
4           UINT i = 0;
5           char buf[80];
6           UINT sz = mHeight * mWidth; //sz = 327,680
7           while (i < sz) {
8                  sprintf_s(buf, sizeof(buf), "%d", pSrc[i]); 
9                  file.Write(buf, strlen(buf));
10                 i++;
11                 if (i < sz)  
12                        file.Write(",", 1);
13                 if (i % mWidth == 0) 
14                        file.Write("\r\n", 2);
15  }

所有值都在 640x512 .csv 文件中输出,其中包含表示摄氏度的整数。

4

2 回答 2

1

刚刚想通了!下面是似乎完成工作的实现。

int sz = mHeight * mWidth;

std::string uniqueCSV = "Frame " + to_string(miCurrentCSVImage + 1) + ".csv";
std::string file = capFile + "/" + uniqueCSV;
std::ofstream out;
out.open(file);

std::string data = "";

int i = 0;
while (i < sz) {
    data += to_string(pSrc[i]);
    i++;
    if (i < sz)
        data += ",";
    if (i % mWidth == 0)
        data += "\n";
}

out << data;
out.close();
miCurrentCSVImage++;
于 2019-02-20T17:31:05.290 回答
0

如何尝试使用一整行大小的字符串

然后在每次迭代中将您的数据添加到 buf 和一个逗号(通过将整行连接到 buf)& 当你到达

 if (i % mWidth == 0)

将整行写入 CFile 并使用

像这样的东西

UINT sz = mHeight * mWidth; std::string line = "";
while (int i < sz) { line += std::to_string(pSrc[i])) + ','; i++;
if (i % mWidth == 0) { 
file.Write(line.c_str(), line.size()); 
file.Write("\r\n", 2); 
line = ""; } }
于 2019-01-30T23:49:45.283 回答