Why does MATLAB's permute not need extra memory?

前端 未结 2 2222
再見小時候
再見小時候 2021-02-19 04:17

The permutation operation needs to output a different matrix to the output, it\'s not like reshape, where the data is not modified, permute does modify the

2条回答
  •  眼角桃花
    2021-02-19 04:29

    Your argument is flawed because the MATLAB memory profiler is not telling you the truth!

    The permute method in fact does create a second copy of the matrix with the data permuted and returns it...

    I just tried this myself:

    • In Windows 10, I opened the "task manager" on the "performance" tab with the "memory" graphs in view. I also set the "update speed" to "high" to get a finer time resolution.

    • I only have 8 gigs of RAM on my laptop, so to avoid thrashing I modified your function as:

      function out = mtest()
          out = rand([1e3,5e2,5e2]);  % about 1.8 GB = 1e3*5e2*5e2*8/2^30
          out = permute(out, [3 2 1]);
      end
      
    • I then ran the function simply as:

      %clear a
      a = mtest();
      

      and watched the memory usage; It went from 1.8 gigs in use, and rose to 5.2 then quickly down to 3.6 gigs. This confirms that a copy was created.

    I also repeated the test under perfmon.exe which showed the same pattern:

    you can see how at its peak the function reached twice as much memory usage as when it returned.

    While this is not exactly the best way to profile memory usage (better use a proper memory profiler, something like Intel Inspector XE), it does show to some degree that permute is indeed not working in-place.

提交回复
热议问题