|
| 1 | +#!/usr/bin/env python |
| 2 | +# Copyright (c) 2023-2024 Geosiris. |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +""" |
| 5 | +Example demonstrating the keep_open feature of EpcStreamReader. |
| 6 | +
|
| 7 | +This example shows how using keep_open=True improves performance when |
| 8 | +performing multiple operations on an EPC file by keeping the ZIP file |
| 9 | +open instead of reopening it for each operation. |
| 10 | +""" |
| 11 | + |
| 12 | +import time |
| 13 | +import sys |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | +# Add src directory to path |
| 17 | +src_path = Path(__file__).parent.parent / "src" |
| 18 | +sys.path.insert(0, str(src_path)) |
| 19 | + |
| 20 | +from energyml.utils.epc_stream import EpcStreamReader |
| 21 | + |
| 22 | + |
| 23 | +def benchmark_without_keep_open(epc_path: str, num_operations: int = 10): |
| 24 | + """Benchmark reading objects without keep_open.""" |
| 25 | + print(f"\nBenchmark WITHOUT keep_open ({num_operations} operations):") |
| 26 | + print("=" * 60) |
| 27 | + |
| 28 | + start = time.time() |
| 29 | + |
| 30 | + # Create reader without keep_open |
| 31 | + with EpcStreamReader(epc_path, keep_open=False, cache_size=5) as reader: |
| 32 | + metadata_list = reader.list_object_metadata() |
| 33 | + |
| 34 | + if not metadata_list: |
| 35 | + print(" No objects in EPC file") |
| 36 | + return 0 |
| 37 | + |
| 38 | + # Perform multiple read operations |
| 39 | + for i in range(min(num_operations, len(metadata_list))): |
| 40 | + meta = metadata_list[i % len(metadata_list)] |
| 41 | + if meta.identifier: |
| 42 | + _ = reader.get_object_by_identifier(meta.identifier) |
| 43 | + if i == 0: |
| 44 | + print(f" First object: {meta.object_type}") |
| 45 | + |
| 46 | + elapsed = time.time() - start |
| 47 | + print(f" Time: {elapsed:.4f}s") |
| 48 | + print(f" Avg per operation: {elapsed / num_operations:.4f}s") |
| 49 | + |
| 50 | + return elapsed |
| 51 | + |
| 52 | + |
| 53 | +def benchmark_with_keep_open(epc_path: str, num_operations: int = 10): |
| 54 | + """Benchmark reading objects with keep_open.""" |
| 55 | + print(f"\nBenchmark WITH keep_open ({num_operations} operations):") |
| 56 | + print("=" * 60) |
| 57 | + |
| 58 | + start = time.time() |
| 59 | + |
| 60 | + # Create reader with keep_open |
| 61 | + with EpcStreamReader(epc_path, keep_open=True, cache_size=5) as reader: |
| 62 | + metadata_list = reader.list_object_metadata() |
| 63 | + |
| 64 | + if not metadata_list: |
| 65 | + print(" No objects in EPC file") |
| 66 | + return 0 |
| 67 | + |
| 68 | + # Perform multiple read operations |
| 69 | + for i in range(min(num_operations, len(metadata_list))): |
| 70 | + meta = metadata_list[i % len(metadata_list)] |
| 71 | + if meta.identifier: |
| 72 | + _ = reader.get_object_by_identifier(meta.identifier) |
| 73 | + if i == 0: |
| 74 | + print(f" First object: {meta.object_type}") |
| 75 | + |
| 76 | + elapsed = time.time() - start |
| 77 | + print(f" Time: {elapsed:.4f}s") |
| 78 | + print(f" Avg per operation: {elapsed / num_operations:.4f}s") |
| 79 | + |
| 80 | + return elapsed |
| 81 | + |
| 82 | + |
| 83 | +def demonstrate_file_modification_with_keep_open(epc_path: str): |
| 84 | + """Demonstrate that modifications work correctly with keep_open.""" |
| 85 | + print("\nDemonstrating file modifications with keep_open:") |
| 86 | + print("=" * 60) |
| 87 | + |
| 88 | + with EpcStreamReader(epc_path, keep_open=True) as reader: |
| 89 | + metadata_list = reader.list_object_metadata() |
| 90 | + original_count = len(metadata_list) |
| 91 | + print(f" Original object count: {original_count}") |
| 92 | + |
| 93 | + if metadata_list: |
| 94 | + # Get first object |
| 95 | + first_obj = reader.get_object_by_identifier(metadata_list[0].identifier) |
| 96 | + print(f" Retrieved object: {metadata_list[0].object_type}") |
| 97 | + |
| 98 | + # Update the object (re-add it) |
| 99 | + identifier = reader.update_object(first_obj) |
| 100 | + print(f" Updated object: {identifier}") |
| 101 | + |
| 102 | + # Verify we can still read it after update |
| 103 | + updated_obj = reader.get_object_by_identifier(identifier) |
| 104 | + assert updated_obj is not None, "Failed to read object after update" |
| 105 | + print(" ✓ Object successfully read after update") |
| 106 | + |
| 107 | + # Verify object count is the same |
| 108 | + new_metadata_list = reader.list_object_metadata() |
| 109 | + new_count = len(new_metadata_list) |
| 110 | + print(f" New object count: {new_count}") |
| 111 | + |
| 112 | + if new_count == original_count: |
| 113 | + print(" ✓ Object count unchanged (correct)") |
| 114 | + else: |
| 115 | + print(f" ✗ Object count changed: {original_count} -> {new_count}") |
| 116 | + |
| 117 | + |
| 118 | +def demonstrate_proper_cleanup(): |
| 119 | + """Demonstrate that persistent ZIP file is properly closed.""" |
| 120 | + print("\nDemonstrating proper cleanup:") |
| 121 | + print("=" * 60) |
| 122 | + |
| 123 | + temp_path = "temp_test.epc" |
| 124 | + |
| 125 | + try: |
| 126 | + # Create a temporary EPC file |
| 127 | + reader = EpcStreamReader(temp_path, keep_open=True) |
| 128 | + print(" Created EpcStreamReader with keep_open=True") |
| 129 | + |
| 130 | + # Manually close |
| 131 | + reader.close() |
| 132 | + print(" ✓ Manually closed reader") |
| 133 | + |
| 134 | + # Create another reader and let it go out of scope |
| 135 | + reader2 = EpcStreamReader(temp_path, keep_open=True) |
| 136 | + print(" Created second EpcStreamReader") |
| 137 | + del reader2 |
| 138 | + print(" ✓ Reader deleted (automatic cleanup via __del__)") |
| 139 | + |
| 140 | + # Create reader in context manager |
| 141 | + with EpcStreamReader(temp_path, keep_open=True) as _: |
| 142 | + print(" Created third EpcStreamReader in context manager") |
| 143 | + print(" ✓ Context manager exited (automatic cleanup)") |
| 144 | + |
| 145 | + finally: |
| 146 | + # Clean up temp file |
| 147 | + if Path(temp_path).exists(): |
| 148 | + Path(temp_path).unlink() |
| 149 | + |
| 150 | + |
| 151 | +def main(): |
| 152 | + """Run all examples.""" |
| 153 | + print("EpcStreamReader keep_open Feature Demonstration") |
| 154 | + print("=" * 60) |
| 155 | + |
| 156 | + # You'll need to provide a valid EPC file path |
| 157 | + epc_path = "wip/epc_test.epc" |
| 158 | + |
| 159 | + if not Path(epc_path).exists(): |
| 160 | + print(f"\nError: EPC file not found: {epc_path}") |
| 161 | + print("Please provide a valid EPC file path in the script.") |
| 162 | + print("\nRunning cleanup demonstration only:") |
| 163 | + demonstrate_proper_cleanup() |
| 164 | + return |
| 165 | + |
| 166 | + try: |
| 167 | + # Run benchmarks |
| 168 | + num_ops = 20 |
| 169 | + |
| 170 | + time_without = benchmark_without_keep_open(epc_path, num_ops) |
| 171 | + time_with = benchmark_with_keep_open(epc_path, num_ops) |
| 172 | + |
| 173 | + # Show comparison |
| 174 | + print("\n" + "=" * 60) |
| 175 | + print("Performance Comparison:") |
| 176 | + print("=" * 60) |
| 177 | + if time_with > 0 and time_without > 0: |
| 178 | + speedup = time_without / time_with |
| 179 | + improvement = ((time_without - time_with) / time_without) * 100 |
| 180 | + print(f" Speedup: {speedup:.2f}x") |
| 181 | + print(f" Improvement: {improvement:.1f}%") |
| 182 | + |
| 183 | + if speedup > 1.1: |
| 184 | + print("\n ✓ keep_open=True significantly improves performance!") |
| 185 | + elif speedup > 1.0: |
| 186 | + print("\n ✓ keep_open=True slightly improves performance") |
| 187 | + else: |
| 188 | + print("\n Note: For this workload, the difference is minimal") |
| 189 | + print(" (cache effects or small file)") |
| 190 | + |
| 191 | + # Demonstrate modifications |
| 192 | + demonstrate_file_modification_with_keep_open(epc_path) |
| 193 | + |
| 194 | + # Demonstrate cleanup |
| 195 | + demonstrate_proper_cleanup() |
| 196 | + |
| 197 | + print("\n" + "=" * 60) |
| 198 | + print("All demonstrations completed successfully!") |
| 199 | + print("=" * 60) |
| 200 | + |
| 201 | + except Exception as e: |
| 202 | + print(f"\nError: {e}") |
| 203 | + import traceback |
| 204 | + |
| 205 | + traceback.print_exc() |
| 206 | + |
| 207 | + |
| 208 | +if __name__ == "__main__": |
| 209 | + main() |
0 commit comments