Created
August 26, 2024 12:46
-
-
Save olidroide/3cdc293b239f04c223384ca244403ad8 to your computer and use it in GitHub Desktop.
Example of use MMAP for read large file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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