

Tic, for idx = 1:length(data), fwrite(fid,data(idx)) end, toc Tic, for idx = 1: length (data ), fwrite (fid,data (idx ) ) end, toc fclose (fid ) ĭata = randi(250,1e6,1) % 1M integer values between 1-250 Writing data without buffering in this manner severely degrades I/O performance:ĭata = randi ( 250,1e6, 1 ) % 1M integer values between 1-250 % Standard unbuffered writing - slow The only exception to this rule is when the file was fopen‘ed with the 'W' or 'A' specifiers (which for some inexplicable reason is NOT mentioned in the technical solution!), or when outputting to the MATLAB’s Command Window (more precisely, to STDOUT (fid=1) and STDERR (fid=2)).

This is not mentioned outright in the main documentation, but is stated loud and clear in the official technical support solution 1-PV371. Unlike C/C++’s implementation, Matlab’s fprintf and fwrite automatically flush the output buffer whenever they are called, even when '\n' is not present in the output stream. Today’s article applies equally to the fprintf function, which is used to save data in text format.Īpparently, there are things to be learned even with such standard low-level functions there’s a deep moral here I guess. This function is in fact so low-level, and is used so often, that some readers may be surprised that its default speed can be improved. In many cases, using fwrite provides the fastest alternative to saving data files ( save(…,’-v6′) coming a close second). Today’s post is about the well-known fwrite function, which is used to write binary data to file. So taking some artistic liberty coupled with some influence over this blog’s owner, I’ll mention some of these interesting discoveries here, even if they are not strictly-speaking undocumented. In many cases these aspects are not un-documented per-se, but are certainly not well known in the Matlab community. During my work on this book, I encounter many surprising aspects of Matlab performance.

Readers of this blog are probably aware by now that I am currently writing my second book, MATLAB Performance Tuning (expected publication date: early 2014, CRC Press).
