2016年8月8日 星期一

c++快速讀取(空白)分隔文字檔案

研究了一陣子終於可以快速讀取檔案(一開始讀取時間為7s,改善後為300ms)
概念是把全部的檔案都先load到記憶體中
並且先掃過檔案,知道elements數,產生靜態陣列
最後再用strtod將記憶體中的char*轉換成double
strtod可以回傳轉換終止的ptr
atod可以轉換,但沒有回傳ptr

FILE* pFile = fopen("text.asc", "r"); fseek(pFile, 0, SEEK_END); int charCount = ftell(pFile); rewind(pFile);
// allocate memory to open the whole file char* charBuffer = (char*)malloc(sizeof(char) * charCount); fread(charBuffer, charCount, 1, pFile); // get file elements count
for (int i = 0; i < charCount; i++) { switch (charBuffer[i]) { case '\n': case '\r': case ' ': numberCount++; break; default: break; } } fclose(pFile);
// allocate memory to hold the elements double* xyz = (double*)malloc(sizeof(double) * numberCount); double* currentXyz = xyz; char* pNumberEnd = charBuffer; char* pLastNumber = charBuffer + numberCount; int line = 0;
// get the elements while (pNumberEnd < pLastNumber) { *(currentXyz++) = strtod(pNumberEnd, &pNumberEnd); }

沒有留言:

張貼留言