简体   繁体   English

如何使C ++代码更快:使用CFile从相机数据创建.csv文件

[英]How to make C++ code faster: Creating .csv file from camera data using CFile

A high level overview is that 'CFile file's 'file.write()' method gets called for every individual integer data value (line 9) along with line 12, where I write a comma to file. 高级概述是'CFile文件的'file.write()'方法被调用每个单独的整数数据值(第9行)以及第12行,其中我写了一个逗号到文件。

That means that for 327,680 input data integers, there are 2*327,680 = 655,360 file.write() calls. 这意味着对于327,680个输入数据整数,有2 * 327,680 = 655,360个file.write()调用。 The code is very slow because of this and as a result, the code takes 3 seconds to create one csv file. 因此,代码非常慢,因此代码需要3秒才能创建一个csv文件。 How could I improve the efficiency of my code? 我怎样才能提高代码的效率?

Note: I cannot change any declarations of the code. 注意:我无法更改代码的任何声明。 I must use CFile. 我必须使用CFile。 Also, pSrc is of type uint_16_t and is containing the data that I want to store in the .csv file. 此外,pSrc的类型为uint_16_t,并且包含我要存储在.csv文件中的数据。 The data ranges from 0 - 3000 integer values. 数据范围为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  }

All values are outputted in the 640x512 .csv file containing integers representing degrees Celcius. 所有值都在640x512 .csv文件中输出,该文件包含表示摄氏度的整数。

Just Figured it out! 刚搞清楚! Below is the implementation that seemed to get the job done. 以下是似乎完成工作的实现。

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++;

how about trying this use a string of a whole line size 如何尝试使用整行大小的字符串

then at every iteration add your data to the buf and a comma(by concatenating the whole line to the buf) & when you get to 然后在每次迭代时将数据添加到buf和逗号(通过将整行连接到buf)并且当你到达时

 if (i % mWidth == 0)

write the whole line to the CFile and clear you buf using 将整行写入CFile并清除你的buf使用

something like this 这样的事情

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 = ""; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM