Fast code to open and write separate 366 .bin files for each (row,col)

조회 수: 1 (최근 30일)
nlm
nlm 2021년 1월 24일
댓글: nlm 2021년 1월 25일
I am trying to speed up my code. I have a 18000*36000*366 matrix. I split the matrix into 18 bands of each 1000* 36000 .bin files located in 366 folders. I plan to run the same code for 18 times. The problem is it takes 3.5hrs to process 1*36000 like I wanted. It is super slow, any help is appreciated. Below is my code,
for lat = 1:length(lat_band) % length of lat_band = 1000
for lon = 1:36000
if (mask(lat,lon)~=9) % if ocean then skip
data_1km = data; % matrix of size [366,1];
else
data_1km = NaN(366,1);
end
tmp = 'path';
tic
for day = 1:366
fwrite(fopen(sprintf('%s%d', tmp, day, '/band_1.bin'), 'a'), data_1km(day),'double');
end
fclose('all');
clear data_1km day
toc
end
end

채택된 답변

Walter Roberson
Walter Roberson 2021년 1월 24일
That code fopen()'s 366 files inside the loop, which can consume all of the file handles. Better would be
for day = 1:366
fid = fopen(sprintf('%s%d', tmp, day, '/band_1.bin');
fwrite(fid, 'a'), data_1km(day),'double');
fclose(fid)
end
If your system can handle and your process is authorized to have 366 files, then fopen() all of them before for lat and index into the list of handles in the loop. You are doing a lot of fopen() of the same file, and that is expensive.
  댓글 수: 11
Walter Roberson
Walter Roberson 2021년 1월 24일
I will run this code for 18 lat_bands.
What is the file name to be used for band #4 day #7 ? And could you confirm that the variable lat is the one that stores the current lat band number?
nlm
nlm 2021년 1월 25일
Can you tell me why running a code as simple as 0.012 secs. That is a long time isn't it ?
data = NaN(366,1);
tic
for day = 1:ND
fwrite(fids(day), data(day), 'double');
end
toc

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by