Skip to content

Instantly share code, notes, and snippets.

@olidroide
Created August 26, 2024 12:46
Show Gist options
  • Select an option

  • Save olidroide/3cdc293b239f04c223384ca244403ad8 to your computer and use it in GitHub Desktop.

Select an option

Save olidroide/3cdc293b239f04c223384ca244403ad8 to your computer and use it in GitHub Desktop.
Example of use MMAP for read large file
import mmap
import timeit
def test_file_memory_mapping() -> None:
with open('large_file.txt', 'r+b') as f:
mmapped_file = mmap.mmap(f.fileno(), 0)
# Random access to different parts of the file
for i in range(0, len(mmapped_file), 1000):
mmapped_file[i : i + 10]
mmapped_file.close()
def test_file() -> None:
with open('large_file.txt', 'r+b') as f:
# Random access to different parts of the file
for i in range(0, f.seek(0, 2), 1000):
f.seek(i)
f.read(10)
# Number of iterations for the test
iterations = 5
test_file_with_mapping = timeit.timeit('test_file_memory_mapping()', globals=globals(), number=iterations)
test_file_without_mapping = timeit.timeit('test_file()', globals=globals(), number=iterations)
print(f'Without memory mapping: {test_file_without_mapping:.2f} sec')
print(f'With memory mapping: {test_file_with_mapping:.2f} sec')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment