Memory-mapped files with np.memmap in NumPy - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When working with large data files, memory-mapped files let us access data without loading it all at once.
We want to know how the time to access data grows as the file size increases.
Analyze the time complexity of the following code snippet.
import numpy as np
# Create a memory-mapped file for a large array
filename = 'large_array.dat'
shape = (10000, 10000)
# Open memmap in read-write mode
mmap_array = np.memmap(filename, dtype='float64', mode='w+', shape=shape)
# Access a single element
value = mmap_array[5000, 5000]
# Modify a slice
mmap_array[1000:2000, 1000:2000] = 1.0
# Flush changes to disk
mmap_array.flush()
This code creates a large memory-mapped array, reads one element, modifies a slice, and saves changes.
Look at what repeats or takes time in this code.
- Primary operation: Accessing and modifying parts of the large array stored on disk.
- How many times: Reading one element is a single operation; modifying a slice touches many elements (here 1000 x 1000 = 1,000,000 elements).
Accessing one element stays quick no matter the file size.
Modifying a slice grows with the number of elements changed.
| Input Size (n x n) | Approx. Operations for Slice Modification |
|---|---|
| 2,000 x 2,000 | 1,000,000 |
| 10,000 x 10,000 | 1,000,000 |
| 50,000 x 50,000 | 1,000,000 |
Pattern observation: The time to modify stays roughly constant regardless of the total file size, growing linearly with the number of elements changed (area of the slice).
Time Complexity: O(k)
This means the time grows linearly with the number of elements accessed or modified, not the total file size.
[X] Wrong: "Accessing any part of a memory-mapped file always takes time proportional to the whole file size."
[OK] Correct: Memory-mapped files let you access small parts quickly without reading the entire file, so time depends on how much you touch, not the full size.
Understanding how memory-mapped files work helps you handle big data efficiently, a useful skill in many data science tasks.
What if we changed the slice size to the entire array? How would the time complexity change?
Practice
np.memmap in data science?Solution
Step 1: Understand what
np.memmapdoesnp.memmapcreates an array-like object that accesses data stored on disk instead of loading it fully into memory.Step 2: Identify the main advantage
This allows handling very large datasets without using large amounts of RAM, which is the main benefit.Final Answer:
It allows working with large arrays stored on disk without loading all data into memory. -> Option AQuick Check:
Memory-mapped files save RAM by accessing disk data [OK]
- Thinking memmap compresses data
- Assuming memmap loads all data into RAM
- Confusing memmap with GPU acceleration
np.memmap of shape (100, 100) and dtype float32?Solution
Step 1: Check the mode for creating a new file
Mode 'w+' creates a new file or overwrites existing one for reading and writing.Step 2: Verify dtype and shape parameters
The dtype should be 'float32' and shape (100, 100) as given.Final Answer:
np.memmap('data.dat', dtype='float32', mode='w+', shape=(100, 100)) -> Option DQuick Check:
Use mode='w+' to create new memmap files [OK]
- Using mode='r' when creating a new file
- Using incorrect dtype like float64 instead of float32
- Using invalid mode 'rw' which does not exist
import numpy as np filename = 'test.dat' # Create memmap file fp = np.memmap(filename, dtype='int32', mode='w+', shape=(3,3)) fp[:] = np.arange(9).reshape(3,3) fp.flush() # Open memmap file in read mode fp2 = np.memmap(filename, dtype='int32', mode='r', shape=(3,3)) print(fp2[1,2])
Solution
Step 1: Understand the array content
np.arange(9).reshape(3,3) creates a 3x3 array: [[0,1,2],[3,4,5],[6,7,8]]Step 2: Identify the value at position [1,2]
Row 1, column 2 is the third element in second row, which is 5.Final Answer:
5 -> Option BQuick Check:
Index [1,2] in arange(9).reshape(3,3) = 5 [OK]
- Confusing row and column indices
- Forgetting zero-based indexing
- Assuming flush() changes data values
import numpy as np filename = 'data.dat' # Attempt to open memmap file fp = np.memmap(filename, dtype='float64', mode='r+', shape=(10,10)) print(fp[0,0])
Solution
Step 1: Understand mode 'r+'
Mode 'r+' opens an existing file for reading and writing. If file does not exist, it raises an error.Step 2: Check file existence
If 'data.dat' does not exist, this code will raise a FileNotFoundError.Final Answer:
File 'data.dat' does not exist, so mode 'r+' causes an error. -> Option AQuick Check:
Mode 'r+' requires existing file [OK]
- Assuming 'r+' creates new files
- Thinking dtype 'float64' is invalid
- Believing shape must be omitted always
np.memmap is best?Solution
Step 1: Understand memory constraints
The dataset is very large (10000x10000), so loading all data into memory is inefficient.Step 2: Use memmap to read only needed data
Opening with mode='r' allows read-only access. Slicing the first column reads only that part from disk, saving memory.Step 3: Avoid unnecessary writes or full reads
Mode 'w+' overwrites data, which is not desired. Mode 'c' is copy-on-write and still loads data. Loading full array wastes memory.Final Answer:
Open the file with mode='r' and read only the first column slice to compute the mean. -> Option CQuick Check:
Read-only memmap + slice = efficient mean calculation [OK]
- Loading entire large file into memory
- Using mode='w+' which overwrites data
- Not slicing and reading whole array unnecessarily
