-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path09-io-optimization.py
More file actions
1429 lines (1127 loc) · 50.8 KB
/
09-io-optimization.py
File metadata and controls
1429 lines (1127 loc) · 50.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Question: Implement I/O optimization techniques for better performance.
Create examples demonstrating various I/O optimization strategies including
buffering, async I/O, memory mapping, and efficient file operations.
Requirements:
1. Demonstrate file reading/writing optimizations
2. Show buffering strategies
3. Implement async I/O operations
4. Use memory mapping for large files
5. Compare performance of different approaches
Example usage:
optimizer = IOOptimizer()
optimizer.compare_file_operations()
optimizer.demonstrate_async_io()
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
#
# Tips for success:
# - Read the question carefully
# - Think about different I/O bottlenecks
# - Start with simple file operations
# - Test performance differences
# - Don't worry if it's not perfect - learning is a process!
#
# Remember: The best way to learn programming is by doing, not by reading solutions!
#
# Take your time, experiment, and enjoy the learning process!
# Try to implement your solution here:
# (Write your code below this line)
# HINT SECTION (Only look if you're really stuck!)
#
# Think about:
# - What are common I/O bottlenecks?
# - How does buffering improve performance?
# - When should you use async I/O?
# - What are the benefits of memory mapping?
#
# Remember: Start simple and build up complexity gradually!
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Import modules and create basic file operations
# ===============================================================================
# Explanation:
# I/O optimization starts with understanding basic file operations and their
# performance characteristics. We'll create a foundation for testing.
import os
import time
import tempfile
from typing import List, Dict, Any
class BasicFileOperations:
"""Basic file operations for performance comparison."""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
self.test_file = os.path.join(self.temp_dir, "test_file.txt")
def create_test_file(self, size_mb: int = 10) -> str:
"""Create a test file of specified size."""
content = "This is a test line for I/O performance testing.\n" * (size_mb * 1024 * 10)
with open(self.test_file, 'w') as f:
f.write(content)
return self.test_file
def read_file_basic(self, filename: str) -> str:
"""Basic file reading without optimization."""
with open(filename, 'r') as f:
return f.read()
def write_file_basic(self, filename: str, content: str) -> None:
"""Basic file writing without optimization."""
with open(filename, 'w') as f:
f.write(content)
def cleanup(self):
"""Clean up temporary files."""
if os.path.exists(self.test_file):
os.remove(self.test_file)
os.rmdir(self.temp_dir)
# What we accomplished in this step:
# - Created basic file operations class
# - Added test file creation functionality
# - Established foundation for performance testing
# Step 2: Add buffered I/O operations
# ===============================================================================
# Explanation:
# Buffering reduces the number of system calls by reading/writing larger chunks
# of data at once. This significantly improves performance for large files.
import os
import time
import tempfile
from typing import List, Dict, Any
class BasicFileOperations:
"""Basic file operations for performance comparison."""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
self.test_file = os.path.join(self.temp_dir, "test_file.txt")
def create_test_file(self, size_mb: int = 10) -> str:
"""Create a test file of specified size."""
content = "This is a test line for I/O performance testing.\n" * (size_mb * 1024 * 10)
with open(self.test_file, 'w') as f:
f.write(content)
return self.test_file
def read_file_basic(self, filename: str) -> str:
"""Basic file reading without optimization."""
with open(filename, 'r') as f:
return f.read()
def write_file_basic(self, filename: str, content: str) -> None:
"""Basic file writing without optimization."""
with open(filename, 'w') as f:
f.write(content)
def cleanup(self):
"""Clean up temporary files."""
if os.path.exists(self.test_file):
os.remove(self.test_file)
os.rmdir(self.temp_dir)
class BufferedFileOperations:
"""Buffered file operations for improved performance."""
def __init__(self, buffer_size: int = 8192):
self.buffer_size = buffer_size
self.temp_dir = tempfile.mkdtemp()
def read_file_buffered(self, filename: str) -> str:
"""Read file using custom buffer size."""
content = []
with open(filename, 'r', buffering=self.buffer_size) as f:
while True:
chunk = f.read(self.buffer_size)
if not chunk:
break
content.append(chunk)
return ''.join(content)
def write_file_buffered(self, filename: str, content: str) -> None:
"""Write file using buffered operations."""
with open(filename, 'w', buffering=self.buffer_size) as f:
# Write in chunks to demonstrate buffering
for i in range(0, len(content), self.buffer_size):
f.write(content[i:i + self.buffer_size])
def copy_file_buffered(self, source: str, destination: str) -> None:
"""Copy file using buffered operations."""
with open(source, 'rb') as src, open(destination, 'wb') as dst:
while True:
chunk = src.read(self.buffer_size)
if not chunk:
break
dst.write(chunk)
def read_lines_buffered(self, filename: str) -> List[str]:
"""Read file line by line with buffering."""
lines = []
with open(filename, 'r', buffering=self.buffer_size) as f:
for line in f:
lines.append(line.strip())
return lines
def cleanup(self):
"""Clean up temporary files."""
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
# What we accomplished in this step:
# - Added buffered file operations with custom buffer sizes
# - Implemented chunked reading and writing
# - Added line-by-line reading with buffering
# Step 3: Add async I/O operations
# ===============================================================================
# Explanation:
# Async I/O allows non-blocking operations, enabling concurrent processing
# of multiple I/O operations for better performance in I/O-bound applications.
import os
import time
import tempfile
import asyncio
import aiofiles
from typing import List, Dict, Any
class BasicFileOperations:
"""Basic file operations for performance comparison."""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
self.test_file = os.path.join(self.temp_dir, "test_file.txt")
def create_test_file(self, size_mb: int = 10) -> str:
"""Create a test file of specified size."""
content = "This is a test line for I/O performance testing.\n" * (size_mb * 1024 * 10)
with open(self.test_file, 'w') as f:
f.write(content)
return self.test_file
def read_file_basic(self, filename: str) -> str:
"""Basic file reading without optimization."""
with open(filename, 'r') as f:
return f.read()
def write_file_basic(self, filename: str, content: str) -> None:
"""Basic file writing without optimization."""
with open(filename, 'w') as f:
f.write(content)
def cleanup(self):
"""Clean up temporary files."""
if os.path.exists(self.test_file):
os.remove(self.test_file)
os.rmdir(self.temp_dir)
class BufferedFileOperations:
"""Buffered file operations for improved performance."""
def __init__(self, buffer_size: int = 8192):
self.buffer_size = buffer_size
self.temp_dir = tempfile.mkdtemp()
def read_file_buffered(self, filename: str) -> str:
"""Read file using custom buffer size."""
content = []
with open(filename, 'r', buffering=self.buffer_size) as f:
while True:
chunk = f.read(self.buffer_size)
if not chunk:
break
content.append(chunk)
return ''.join(content)
def write_file_buffered(self, filename: str, content: str) -> None:
"""Write file using buffered operations."""
with open(filename, 'w', buffering=self.buffer_size) as f:
# Write in chunks to demonstrate buffering
for i in range(0, len(content), self.buffer_size):
f.write(content[i:i + self.buffer_size])
def copy_file_buffered(self, source: str, destination: str) -> None:
"""Copy file using buffered operations."""
with open(source, 'rb') as src, open(destination, 'wb') as dst:
while True:
chunk = src.read(self.buffer_size)
if not chunk:
break
dst.write(chunk)
def read_lines_buffered(self, filename: str) -> List[str]:
"""Read file line by line with buffering."""
lines = []
with open(filename, 'r', buffering=self.buffer_size) as f:
for line in f:
lines.append(line.strip())
return lines
def cleanup(self):
"""Clean up temporary files."""
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
class AsyncFileOperations:
"""Async file operations for concurrent I/O."""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
async def read_file_async(self, filename: str) -> str:
"""Read file asynchronously."""
async with aiofiles.open(filename, 'r') as f:
return await f.read()
async def write_file_async(self, filename: str, content: str) -> None:
"""Write file asynchronously."""
async with aiofiles.open(filename, 'w') as f:
await f.write(content)
async def read_multiple_files_async(self, filenames: List[str]) -> List[str]:
"""Read multiple files concurrently."""
tasks = [self.read_file_async(filename) for filename in filenames]
return await asyncio.gather(*tasks)
async def write_multiple_files_async(self, file_data: Dict[str, str]) -> None:
"""Write multiple files concurrently."""
tasks = [
self.write_file_async(filename, content)
for filename, content in file_data.items()
]
await asyncio.gather(*tasks)
async def copy_file_async(self, source: str, destination: str, chunk_size: int = 8192) -> None:
"""Copy file asynchronously with chunked reading."""
async with aiofiles.open(source, 'rb') as src:
async with aiofiles.open(destination, 'wb') as dst:
while True:
chunk = await src.read(chunk_size)
if not chunk:
break
await dst.write(chunk)
async def process_files_concurrently(self, filenames: List[str], processor_func) -> List[Any]:
"""Process multiple files concurrently with a custom function."""
tasks = [processor_func(filename) for filename in filenames]
return await asyncio.gather(*tasks)
def cleanup(self):
"""Clean up temporary files."""
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
# What we accomplished in this step:
# - Added async file operations using aiofiles
# - Implemented concurrent file reading and writing
# - Added support for processing multiple files simultaneously
# Step 4: Add memory mapping operations
# ===============================================================================
# Explanation:
# Memory mapping allows direct access to file contents in memory, providing
# very fast random access and efficient handling of large files.
import os
import time
import tempfile
import asyncio
import aiofiles
import mmap
from typing import List, Dict, Any
class BasicFileOperations:
"""Basic file operations for performance comparison."""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
self.test_file = os.path.join(self.temp_dir, "test_file.txt")
def create_test_file(self, size_mb: int = 10) -> str:
"""Create a test file of specified size."""
content = "This is a test line for I/O performance testing.\n" * (size_mb * 1024 * 10)
with open(self.test_file, 'w') as f:
f.write(content)
return self.test_file
def read_file_basic(self, filename: str) -> str:
"""Basic file reading without optimization."""
with open(filename, 'r') as f:
return f.read()
def write_file_basic(self, filename: str, content: str) -> None:
"""Basic file writing without optimization."""
with open(filename, 'w') as f:
f.write(content)
def cleanup(self):
"""Clean up temporary files."""
if os.path.exists(self.test_file):
os.remove(self.test_file)
os.rmdir(self.temp_dir)
class BufferedFileOperations:
"""Buffered file operations for improved performance."""
def __init__(self, buffer_size: int = 8192):
self.buffer_size = buffer_size
self.temp_dir = tempfile.mkdtemp()
def read_file_buffered(self, filename: str) -> str:
"""Read file using custom buffer size."""
content = []
with open(filename, 'r', buffering=self.buffer_size) as f:
while True:
chunk = f.read(self.buffer_size)
if not chunk:
break
content.append(chunk)
return ''.join(content)
def write_file_buffered(self, filename: str, content: str) -> None:
"""Write file using buffered operations."""
with open(filename, 'w', buffering=self.buffer_size) as f:
# Write in chunks to demonstrate buffering
for i in range(0, len(content), self.buffer_size):
f.write(content[i:i + self.buffer_size])
def copy_file_buffered(self, source: str, destination: str) -> None:
"""Copy file using buffered operations."""
with open(source, 'rb') as src, open(destination, 'wb') as dst:
while True:
chunk = src.read(self.buffer_size)
if not chunk:
break
dst.write(chunk)
def read_lines_buffered(self, filename: str) -> List[str]:
"""Read file line by line with buffering."""
lines = []
with open(filename, 'r', buffering=self.buffer_size) as f:
for line in f:
lines.append(line.strip())
return lines
def cleanup(self):
"""Clean up temporary files."""
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
class AsyncFileOperations:
"""Async file operations for concurrent I/O."""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
async def read_file_async(self, filename: str) -> str:
"""Read file asynchronously."""
async with aiofiles.open(filename, 'r') as f:
return await f.read()
async def write_file_async(self, filename: str, content: str) -> None:
"""Write file asynchronously."""
async with aiofiles.open(filename, 'w') as f:
await f.write(content)
async def read_multiple_files_async(self, filenames: List[str]) -> List[str]:
"""Read multiple files concurrently."""
tasks = [self.read_file_async(filename) for filename in filenames]
return await asyncio.gather(*tasks)
async def write_multiple_files_async(self, file_data: Dict[str, str]) -> None:
"""Write multiple files concurrently."""
tasks = [
self.write_file_async(filename, content)
for filename, content in file_data.items()
]
await asyncio.gather(*tasks)
async def copy_file_async(self, source: str, destination: str, chunk_size: int = 8192) -> None:
"""Copy file asynchronously with chunked reading."""
async with aiofiles.open(source, 'rb') as src:
async with aiofiles.open(destination, 'wb') as dst:
while True:
chunk = await src.read(chunk_size)
if not chunk:
break
await dst.write(chunk)
async def process_files_concurrently(self, filenames: List[str], processor_func) -> List[Any]:
"""Process multiple files concurrently with a custom function."""
tasks = [processor_func(filename) for filename in filenames]
return await asyncio.gather(*tasks)
def cleanup(self):
"""Clean up temporary files."""
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
class MemoryMappedOperations:
"""Memory-mapped file operations for large file handling."""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
def read_file_mmap(self, filename: str) -> str:
"""Read file using memory mapping."""
with open(filename, 'r+b') as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
return mm.read().decode('utf-8')
def search_in_file_mmap(self, filename: str, pattern: bytes) -> List[int]:
"""Search for pattern in file using memory mapping."""
positions = []
with open(filename, 'r+b') as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
start = 0
while True:
pos = mm.find(pattern, start)
if pos == -1:
break
positions.append(pos)
start = pos + 1
return positions
def read_file_slice_mmap(self, filename: str, start: int, length: int) -> str:
"""Read a specific slice of file using memory mapping."""
with open(filename, 'r+b') as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
mm.seek(start)
return mm.read(length).decode('utf-8')
def modify_file_mmap(self, filename: str, position: int, new_data: bytes) -> None:
"""Modify file at specific position using memory mapping."""
with open(filename, 'r+b') as f:
with mmap.mmap(f.fileno(), 0) as mm:
mm.seek(position)
mm.write(new_data)
mm.flush()
def copy_file_mmap(self, source: str, destination: str) -> None:
"""Copy file using memory mapping."""
with open(source, 'r+b') as src_f:
with mmap.mmap(src_f.fileno(), 0, access=mmap.ACCESS_READ) as src_mm:
with open(destination, 'w+b') as dst_f:
dst_f.write(src_mm.read())
def analyze_file_mmap(self, filename: str) -> Dict[str, Any]:
"""Analyze file content using memory mapping."""
stats = {
'size': 0,
'lines': 0,
'words': 0,
'chars': 0
}
with open(filename, 'r+b') as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
stats['size'] = len(mm)
content = mm.read().decode('utf-8')
stats['lines'] = content.count('\n')
stats['words'] = len(content.split())
stats['chars'] = len(content)
return stats
def cleanup(self):
"""Clean up temporary files."""
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
# What we accomplished in this step:
# - Added memory-mapped file operations for large files
# - Implemented efficient file searching and slicing
# - Added in-place file modification capabilities
# Step 5: Create performance comparison and optimization manager
# ===============================================================================
# Explanation:
# The IOOptimizer class brings together all optimization techniques and provides
# performance comparisons to demonstrate the benefits of each approach.
import os
import time
import tempfile
import asyncio
import aiofiles
import mmap
from typing import List, Dict, Any, Callable
class BasicFileOperations:
"""Basic file operations for performance comparison."""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
self.test_file = os.path.join(self.temp_dir, "test_file.txt")
def create_test_file(self, size_mb: int = 10) -> str:
"""Create a test file of specified size."""
content = "This is a test line for I/O performance testing.\n" * (size_mb * 1024 * 10)
with open(self.test_file, 'w') as f:
f.write(content)
return self.test_file
def read_file_basic(self, filename: str) -> str:
"""Basic file reading without optimization."""
with open(filename, 'r') as f:
return f.read()
def write_file_basic(self, filename: str, content: str) -> None:
"""Basic file writing without optimization."""
with open(filename, 'w') as f:
f.write(content)
def cleanup(self):
"""Clean up temporary files."""
if os.path.exists(self.test_file):
os.remove(self.test_file)
os.rmdir(self.temp_dir)
class BufferedFileOperations:
"""Buffered file operations for improved performance."""
def __init__(self, buffer_size: int = 8192):
self.buffer_size = buffer_size
self.temp_dir = tempfile.mkdtemp()
def read_file_buffered(self, filename: str) -> str:
"""Read file using custom buffer size."""
content = []
with open(filename, 'r', buffering=self.buffer_size) as f:
while True:
chunk = f.read(self.buffer_size)
if not chunk:
break
content.append(chunk)
return ''.join(content)
def write_file_buffered(self, filename: str, content: str) -> None:
"""Write file using buffered operations."""
with open(filename, 'w', buffering=self.buffer_size) as f:
# Write in chunks to demonstrate buffering
for i in range(0, len(content), self.buffer_size):
f.write(content[i:i + self.buffer_size])
def copy_file_buffered(self, source: str, destination: str) -> None:
"""Copy file using buffered operations."""
with open(source, 'rb') as src, open(destination, 'wb') as dst:
while True:
chunk = src.read(self.buffer_size)
if not chunk:
break
dst.write(chunk)
def read_lines_buffered(self, filename: str) -> List[str]:
"""Read file line by line with buffering."""
lines = []
with open(filename, 'r', buffering=self.buffer_size) as f:
for line in f:
lines.append(line.strip())
return lines
def cleanup(self):
"""Clean up temporary files."""
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
class AsyncFileOperations:
"""Async file operations for concurrent I/O."""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
async def read_file_async(self, filename: str) -> str:
"""Read file asynchronously."""
async with aiofiles.open(filename, 'r') as f:
return await f.read()
async def write_file_async(self, filename: str, content: str) -> None:
"""Write file asynchronously."""
async with aiofiles.open(filename, 'w') as f:
await f.write(content)
async def read_multiple_files_async(self, filenames: List[str]) -> List[str]:
"""Read multiple files concurrently."""
tasks = [self.read_file_async(filename) for filename in filenames]
return await asyncio.gather(*tasks)
async def write_multiple_files_async(self, file_data: Dict[str, str]) -> None:
"""Write multiple files concurrently."""
tasks = [
self.write_file_async(filename, content)
for filename, content in file_data.items()
]
await asyncio.gather(*tasks)
async def copy_file_async(self, source: str, destination: str, chunk_size: int = 8192) -> None:
"""Copy file asynchronously with chunked reading."""
async with aiofiles.open(source, 'rb') as src:
async with aiofiles.open(destination, 'wb') as dst:
while True:
chunk = await src.read(chunk_size)
if not chunk:
break
await dst.write(chunk)
async def process_files_concurrently(self, filenames: List[str], processor_func) -> List[Any]:
"""Process multiple files concurrently with a custom function."""
tasks = [processor_func(filename) for filename in filenames]
return await asyncio.gather(*tasks)
def cleanup(self):
"""Clean up temporary files."""
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
class MemoryMappedOperations:
"""Memory-mapped file operations for large file handling."""
def __init__(self):
self.temp_dir = tempfile.mkdtemp()
def read_file_mmap(self, filename: str) -> str:
"""Read file using memory mapping."""
with open(filename, 'r+b') as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
return mm.read().decode('utf-8')
def search_in_file_mmap(self, filename: str, pattern: bytes) -> List[int]:
"""Search for pattern in file using memory mapping."""
positions = []
with open(filename, 'r+b') as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
start = 0
while True:
pos = mm.find(pattern, start)
if pos == -1:
break
positions.append(pos)
start = pos + 1
return positions
def read_file_slice_mmap(self, filename: str, start: int, length: int) -> str:
"""Read a specific slice of file using memory mapping."""
with open(filename, 'r+b') as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
mm.seek(start)
return mm.read(length).decode('utf-8')
def modify_file_mmap(self, filename: str, position: int, new_data: bytes) -> None:
"""Modify file at specific position using memory mapping."""
with open(filename, 'r+b') as f:
with mmap.mmap(f.fileno(), 0) as mm:
mm.seek(position)
mm.write(new_data)
mm.flush()
def copy_file_mmap(self, source: str, destination: str) -> None:
"""Copy file using memory mapping."""
with open(source, 'r+b') as src_f:
with mmap.mmap(src_f.fileno(), 0, access=mmap.ACCESS_READ) as src_mm:
with open(destination, 'w+b') as dst_f:
dst_f.write(src_mm.read())
def analyze_file_mmap(self, filename: str) -> Dict[str, Any]:
"""Analyze file content using memory mapping."""
stats = {
'size': 0,
'lines': 0,
'words': 0,
'chars': 0
}
with open(filename, 'r+b') as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
stats['size'] = len(mm)
content = mm.read().decode('utf-8')
stats['lines'] = content.count('\n')
stats['words'] = len(content.split())
stats['chars'] = len(content)
return stats
def cleanup(self):
"""Clean up temporary files."""
import shutil
if os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
class IOOptimizer:
"""Main class that demonstrates and compares I/O optimization techniques."""
def __init__(self):
self.basic_ops = BasicFileOperations()
self.buffered_ops = BufferedFileOperations()
self.async_ops = AsyncFileOperations()
self.mmap_ops = MemoryMappedOperations()
self.test_files = []
def measure_time(self, func: Callable, *args, **kwargs) -> tuple:
"""Measure execution time of a function."""
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
return result, end_time - start_time
async def measure_time_async(self, coro, *args, **kwargs) -> tuple:
"""Measure execution time of an async function."""
start_time = time.time()
result = await coro(*args, **kwargs)
end_time = time.time()
return result, end_time - start_time
def compare_file_operations(self, file_size_mb: int = 5) -> Dict[str, float]:
"""Compare performance of different file reading methods."""
print(f"=== Comparing File Reading Performance ({file_size_mb}MB file) ===\n")
# Create test file
test_file = self.basic_ops.create_test_file(file_size_mb)
self.test_files.append(test_file)
results = {}
# Basic reading
_, basic_time = self.measure_time(self.basic_ops.read_file_basic, test_file)
results['Basic'] = basic_time
print(f"Basic reading: {basic_time:.4f} seconds")
# Buffered reading
_, buffered_time = self.measure_time(self.buffered_ops.read_file_buffered, test_file)
results['Buffered'] = buffered_time
print(f"Buffered reading: {buffered_time:.4f} seconds")
# Memory mapped reading
_, mmap_time = self.measure_time(self.mmap_ops.read_file_mmap, test_file)
results['Memory Mapped'] = mmap_time
print(f"Memory mapped reading: {mmap_time:.4f} seconds")
print(f"\nPerformance improvement:")
print(f"Buffered vs Basic: {(basic_time/buffered_time):.2f}x faster")
print(f"Memory Mapped vs Basic: {(basic_time/mmap_time):.2f}x faster")
print()
return results
async def demonstrate_async_io(self) -> None:
"""Demonstrate async I/O performance benefits."""
print("=== Demonstrating Async I/O Performance ===\n")
# Create multiple test files
file_data = {}
for i in range(5):
filename = os.path.join(self.async_ops.temp_dir, f"async_test_{i}.txt")
content = f"Test file {i} content\n" * 1000
file_data[filename] = content
self.test_files.append(filename)
# Sequential writing
start_time = time.time()
for filename, content in file_data.items():
with open(filename, 'w') as f:
f.write(content)
sequential_time = time.time() - start_time
# Async concurrent writing
_, async_time = await self.measure_time_async(
self.async_ops.write_multiple_files_async, file_data
)
print(f"Sequential writing: {sequential_time:.4f} seconds")
print(f"Async concurrent writing: {async_time:.4f} seconds")
print(f"Async improvement: {(sequential_time/async_time):.2f}x faster")
print()
def demonstrate_memory_mapping_benefits(self) -> None:
"""Demonstrate memory mapping benefits for large file operations."""
print("=== Demonstrating Memory Mapping Benefits ===\n")
# Create a large test file
large_file = self.basic_ops.create_test_file(20) # 20MB file
self.test_files.append(large_file)
# Search for pattern using basic method
pattern = b"performance"
def basic_search():
with open(large_file, 'rb') as f:
content = f.read()
positions = []
start = 0
while True:
pos = content.find(pattern, start)
if pos == -1:
break
positions.append(pos)
start = pos + 1
return positions
_, basic_search_time = self.measure_time(basic_search)
_, mmap_search_time = self.measure_time(
self.mmap_ops.search_in_file_mmap, large_file, pattern
)
print(f"Basic pattern search: {basic_search_time:.4f} seconds")
print(f"Memory mapped search: {mmap_search_time:.4f} seconds")
print(f"Memory mapping improvement: {(basic_search_time/mmap_search_time):.2f}x faster")
# Demonstrate file analysis
stats = self.mmap_ops.analyze_file_mmap(large_file)
print(f"\nFile analysis results:")
print(f"Size: {stats['size']:,} bytes")
print(f"Lines: {stats['lines']:,}")
print(f"Words: {stats['words']:,}")
print(f"Characters: {stats['chars']:,}")
print()
def cleanup(self):
"""Clean up all temporary files and directories."""
self.basic_ops.cleanup()
self.buffered_ops.cleanup()
self.async_ops.cleanup()
self.mmap_ops.cleanup()
# Clean up additional test files
for file_path in self.test_files:
if os.path.exists(file_path):
os.remove(file_path)
# What we accomplished in this step:
# - Created comprehensive IOOptimizer class
# - Added performance measurement and comparison tools
# - Implemented demonstrations for all optimization techniques
# Step 6: Test the complete implementation
# ===============================================================================
# Explanation:
# Let's test our I/O optimization implementation with comprehensive demonstrations
# of all techniques and their performance benefits.