Module mmap cho phép ánh xạ file vào bộ nhớ (RAM), thao tác trực tiếp trên bộ nhớ thay vì gọi hệ thống read/write. Tăng hiệu suất khi đọc/ghi file lớn.
Đọc file ánh xạ bộ nhớ
Mở file, tạo đối tượng mmap với ACCESS_READ. Đối tượng mmap hỗ trợ cắt lát (slicing) như bytes.
Ví dụ
import mmap
def read_mmap(fname):
with open(fname, mode="r", encoding="utf8") as fobj:
with mmap.mmap(fobj.fileno(), length=0, access=mmap.ACCESS_READ) as mmap_obj:
print(mmap_obj[4:26])
read_mmap('E:\\test.txt')
Kết quả
'emissions from gaseous'
Tìm kiếm với mmap
So sánh tốc độ tìm kiếm chuỗi giữa đọc toàn file vào RAM (read()) và mmap.find(). mmap thường nhanh hơn vì tránh sao chép dữ liệu.
Ví dụ
import mmap, time
def regular_io_find(fname):
with open(fname, mode="r", encoding="utf-8") as fobj:
text = fobj.read()
text.find("Death ")
def mmap_io_find(fname):
with open(fname, mode="r", encoding="utf-8") as fobj:
with mmap.mmap(fobj.fileno(), length=0, access=mmap.ACCESS_READ) as mmap_obj:
mmap_obj.find(b"Death ")
start_time_r = time.time()
regular_io_find('E:\\emissions.txt')
end_time_r = time.time()
print('Regular read time:', end_time_r - start_time_r)
start_time_m = time.time()
mmap_io_find('E:\\emissions.txt')
end_time_m = time.time()
print('mmap read time:', end_time_m - start_time_m)
Kết quả
Regular read time: 0.0065 mmap read time: 0.0
Ghi file với mmap
Mở file chế độ r+, mmap với ACCESS_WRITE. Ghi dữ liệu bằng cách gán slice, sau đó flush().
Ví dụ
import mmap
def mmap_io_write(fname):
with open(fname, mode="r+") as fobj:
with mmap.mmap(fobj.fileno(), length=0, access=mmap.ACCESS_WRITE) as mmap_obj:
mmap_obj[20:26] = b"Hello!"
mmap_obj.flush()
mmap_io_write('E:\\emissions.txt')
Sau khi chạy, mở file sẽ thấy chuỗi "Hello!" được ghi tại vị trí byte 20-26.