# python/01-profiling-benchmarking.py"""Comprehensive Python performance profiling and benchmarking"""importcProfileimportpstatsimporttimeimportmemory_profilerimportpsutilimportosfromtypingimportList,Dict,Any,Callable,Optionalfromfunctoolsimportwrapsimporttracemallocimportline_profilerclassPerformanceProfiler:"""Comprehensive performance profiling tools"""def__init__(self):self.profiler=cProfile.Profile()self.memory_traces=[]defprofile_function(self,func:Callable)->Callable:"""Decorator to profile a function"""@wraps(func)defwrapper(*args,**kwargs):# Start profilingself.profiler.enable()start_time=time.time()start_memory=psutil.Process().memory_info().rss# Execute functionresult=func(*args,**kwargs)# Stop profilingend_time=time.time()end_memory=psutil.Process().memory_info().rssself.profiler.disable()# Record metricsexecution_time=end_time-start_timememory_used=end_memory-start_memoryprint(f"Function: {func.__name__}")print(f"Execution time: {execution_time:.4f} seconds")print(f"Memory used: {memory_used/1024/1024:.2f} MB")returnresultreturnwrapperdefprofile_with_cprofile(self,func:Callable,*args,**kwargs)->Dict[str,Any]:"""Profile function with cProfile"""self.profiler.enable()result=func(*args,**kwargs)self.profiler.disable()# Get profiling statsstats=pstats.Stats(self.profiler)stats.sort_stats('cumulative')# Extract key metricstotal_calls=stats.total_callstotal_time=stats.total_ttreturn{"total_calls":total_calls,"total_time":total_time,"stats":stats}defprofile_memory_usage(self,func:Callable,*args,**kwargs)->Dict[str,Any]:"""Profile memory usage of a function"""# Start memory tracingtracemalloc.start()# Execute functionresult=func(*args,**kwargs)# Get memory snapshotcurrent,peak=tracemalloc.get_traced_memory()tracemalloc.stop()return{"current_memory":current,"peak_memory":peak,"result":result}defline_by_line_profile(self,func:Callable,*args,**kwargs)->Dict[str,Any]:"""Line-by-line profiling with line_profiler"""profiler=line_profiler.LineProfiler()profiler.add_function(func)# Execute functionresult=profiler.runcall(func,*args,**kwargs)# Get line-by-line statsprofiler.print_stats()return{"result":result,"profiler":profiler}classBenchmarkSuite:"""Comprehensive benchmarking suite"""def__init__(self):self.benchmarks=[]defbenchmark_function(self,name:str,func:Callable,*args,**kwargs)->Dict[str,Any]:"""Benchmark a single function"""times=[]memory_usage=[]# Warm upfor_inrange(3):func(*args,**kwargs)# Benchmarkfor_inrange(10):start_time=time.time()start_memory=psutil.Process().memory_info().rssresult=func(*args,**kwargs)end_time=time.time()end_memory=psutil.Process().memory_info().rsstimes.append(end_time-start_time)memory_usage.append(end_memory-start_memory)# Calculate statisticsavg_time=sum(times)/len(times)min_time=min(times)max_time=max(times)avg_memory=sum(memory_usage)/len(memory_usage)benchmark_result={"name":name,"avg_time":avg_time,"min_time":min_time,"max_time":max_time,"avg_memory":avg_memory,"times":times,"memory_usage":memory_usage}self.benchmarks.append(benchmark_result)returnbenchmark_resultdefcompare_functions(self,functions:List[tuple])->Dict[str,Any]:"""Compare multiple functions"""results={}forname,func,args,kwargsinfunctions:result=self.benchmark_function(name,func,*args,**kwargs)results[name]=result# Find fastestfastest=min(results.items(),key=lambdax:x[1]["avg_time"])return{"results":results,"fastest":fastest[0],"fastest_time":fastest[1]["avg_time"]}defgenerate_report(self)->str:"""Generate benchmarking report"""ifnotself.benchmarks:return"No benchmarks to report"report="# Performance Benchmark Report\n\n"forbenchmarkinself.benchmarks:report+=f"## {benchmark['name']}\n"report+=f"- Average time: {benchmark['avg_time']:.4f}s\n"report+=f"- Min time: {benchmark['min_time']:.4f}s\n"report+=f"- Max time: {benchmark['max_time']:.4f}s\n"report+=f"- Average memory: {benchmark['avg_memory']/1024/1024:.2f} MB\n\n"returnreport# Usage exampledefexample_slow_function(n:int)->List[int]:"""Example function to profile"""result=[]foriinrange(n):result.append(i*i)returnresultdefexample_fast_function(n:int)->List[int]:"""Optimized version of the function"""return[i*iforiinrange(n)]# Profile functionsprofiler=PerformanceProfiler()@profiler.profile_functiondefprofiled_function():returnexample_slow_function(10000)# Benchmark comparisonbenchmark_suite=BenchmarkSuite()functions_to_compare=[("slow_function",example_slow_function,(10000,),{}),("fast_function",example_fast_function,(10000,),{})]comparison_results=benchmark_suite.compare_functions(functions_to_compare)print(benchmark_suite.generate_report())
# python/02-memory-profiling.py"""Advanced memory profiling and optimization"""importtracemallocimportgcimportsysimportpsutilfromtypingimportList,Dict,Any,Optionalfrommemory_profilerimportprofileimportobjgraphclassMemoryProfiler:"""Advanced memory profiling tools"""def__init__(self):self.memory_snapshots=[]self.gc_stats=[]defstart_memory_tracing(self):"""Start memory tracing"""tracemalloc.start()defstop_memory_tracing(self)->Dict[str,Any]:"""Stop memory tracing and get stats"""current,peak=tracemalloc.get_traced_memory()tracemalloc.stop()return{"current_memory":current,"peak_memory":peak,"current_mb":current/1024/1024,"peak_mb":peak/1024/1024}defget_memory_snapshot(self)->Dict[str,Any]:"""Get current memory snapshot"""process=psutil.Process()memory_info=process.memory_info()snapshot={"rss":memory_info.rss,# Resident Set Size"vms":memory_info.vms,# Virtual Memory Size"percent":process.memory_percent(),"available_memory":psutil.virtual_memory().available}self.memory_snapshots.append(snapshot)returnsnapshotdefanalyze_memory_usage(self,func:Callable,*args,**kwargs)->Dict[str,Any]:"""Analyze memory usage of a function"""# Get initial memoryinitial_snapshot=self.get_memory_snapshot()# Start tracingself.start_memory_tracing()# Execute functionresult=func(*args,**kwargs)# Get final memoryfinal_snapshot=self.get_memory_snapshot()trace_stats=self.stop_memory_tracing()# Calculate memory usagememory_used=final_snapshot["rss"]-initial_snapshot["rss"]return{"initial_memory":initial_snapshot,"final_memory":final_snapshot,"memory_used":memory_used,"trace_stats":trace_stats,"result":result}deffind_memory_leaks(self)->Dict[str,Any]:"""Find potential memory leaks"""# Force garbage collectiongc.collect()# Get object countsobject_counts=objgraph.most_common_types()# Get reference countsreference_counts={}forobj_type,countinobject_counts:ifcount>100:# Threshold for potential leaksreference_counts[obj_type]=countreturn{"object_counts":object_counts,"potential_leaks":reference_counts,"gc_counts":gc.get_count()}defoptimize_memory_usage(self,func:Callable,*args,**kwargs)->Dict[str,Any]:"""Optimize memory usage of a function"""# Analyze current memory usageanalysis=self.analyze_memory_usage(func,*args,**kwargs)# Force garbage collectiongc.collect()# Get memory after GCpost_gc_snapshot=self.get_memory_snapshot()return{"before_optimization":analysis,"after_gc":post_gc_snapshot,"gc_effectiveness":analysis["final_memory"]["rss"]-post_gc_snapshot["rss"]}# Memory optimization patternsclassMemoryOptimizer:"""Memory optimization patterns and techniques"""@staticmethoddefuse_generators(data:List[Any])->List[Any]:"""Use generators instead of lists for large datasets"""return(itemforitemindataifitemisnotNone)@staticmethoddefuse_slots(cls):"""Use __slots__ to reduce memory usage"""classOptimizedClass(cls):__slots__=['attr1','attr2','attr3']returnOptimizedClass@staticmethoddeflazy_loading(data_source:Callable)->Any:"""Implement lazy loading for expensive operations"""classLazyLoader:def__init__(self,loader):self._loader=loaderself._data=Nonedef__getattr__(self,name):ifself._dataisNone:self._data=self._loader()returngetattr(self._data,name)returnLazyLoader(data_source)@staticmethoddefmemory_efficient_processing(data:List[Any],batch_size:int=1000)->List[Any]:"""Process data in batches to reduce memory usage"""results=[]foriinrange(0,len(data),batch_size):batch=data[i:i+batch_size]# Process batchbatch_results=[item*2foriteminbatch]results.extend(batch_results)# Force garbage collection after each batchgc.collect()returnresults# Usage example@profiledefmemory_intensive_function(n:int)->List[int]:"""Function that uses a lot of memory"""data=[]foriinrange(n):data.append(i*i)returndatadefoptimized_memory_function(n:int)->List[int]:"""Memory-optimized version"""return[i*iforiinrange(n)]# Profile memory usagememory_profiler=MemoryProfiler()memory_analysis=memory_profiler.analyze_memory_usage(memory_intensive_function,10000)print(f"Memory used: {memory_analysis['memory_used']/1024/1024:.2f} MB")
# python/03-algorithm-optimization.py"""Algorithm and data structure optimization"""importtimefromtypingimportList,Dict,Any,Optional,Setfromcollectionsimportdefaultdict,deque,CounterimportheapqimportbisectclassAlgorithmOptimizer:"""Algorithm optimization techniques"""@staticmethoddefoptimize_list_operations(data:List[int])->List[int]:"""Optimize list operations"""# Use list comprehension instead of loopsreturn[x*2forxindataifx>0]@staticmethoddefoptimize_dictionary_operations(data:List[str])->Dict[str,int]:"""Optimize dictionary operations"""# Use Counter for countingreturnCounter(data)@staticmethoddefoptimize_set_operations(data1:Set[int],data2:Set[int])->Set[int]:"""Optimize set operations"""# Use set operations for intersection, union, etc.returndata1.intersection(data2)@staticmethoddefoptimize_search_operations(data:List[int],target:int)->Optional[int]:"""Optimize search operations using binary search"""# Use bisect for binary searchindex=bisect.bisect_left(data,target)ifindex<len(data)anddata[index]==target:returnindexreturnNone@staticmethoddefoptimize_heap_operations(data:List[int],k:int)->List[int]:"""Optimize heap operations for top-k elements"""# Use heapq for efficient heap operationsreturnheapq.nlargest(k,data)@staticmethoddefoptimize_string_operations(text:str)->str:"""Optimize string operations"""# Use join instead of concatenationreturn''.join(char.upper()forcharintextifchar.isalpha())classDataStructureOptimizer:"""Data structure optimization patterns"""@staticmethoddefuse_deque_for_fifo(data:List[Any])->deque:"""Use deque for FIFO operations"""returndeque(data)@staticmethoddefuse_defaultdict_for_grouping(data:List[tuple])->Dict[Any,List[Any]]:"""Use defaultdict for grouping operations"""grouped=defaultdict(list)forkey,valueindata:grouped[key].append(value)returngrouped@staticmethoddefuse_counter_for_frequency(data:List[Any])->Counter:"""Use Counter for frequency analysis"""returnCounter(data)@staticmethoddefuse_heap_for_priority_queue(data:List[tuple])->List[tuple]:"""Use heap for priority queue operations"""heapq.heapify(data)returndata# Performance comparison examplesdefcompare_search_algorithms():"""Compare different search algorithms"""data=list(range(1000000))target=500000# Linear searchstart_time=time.time()linear_result=targetindatalinear_time=time.time()-start_time# Binary searchstart_time=time.time()binary_result=AlgorithmOptimizer.optimize_search_operations(data,target)binary_time=time.time()-start_timeprint(f"Linear search: {linear_time:.6f}s")print(f"Binary search: {binary_time:.6f}s")print(f"Speedup: {linear_time/binary_time:.2f}x")defcompare_data_structures():"""Compare different data structures"""data=list(range(10000))# List operationsstart_time=time.time()list_result=[x*2forxindata]list_time=time.time()-start_time# Set operationsdata_set=set(data)start_time=time.time()set_result={x*2forxindata_set}set_time=time.time()-start_timeprint(f"List operations: {list_time:.6f}s")print(f"Set operations: {set_time:.6f}s")
# python/04-concurrency-optimization.py"""Concurrency and parallel processing optimization"""importasyncioimportconcurrent.futuresimportmultiprocessingfromtypingimportList,Callable,AnyimporttimeimportthreadingfromfunctoolsimportpartialclassConcurrencyOptimizer:"""Concurrency optimization patterns"""@staticmethoddefparallel_processing(data:List[Any],func:Callable,max_workers:int=None)->List[Any]:"""Parallel processing with ThreadPoolExecutor"""ifmax_workersisNone:max_workers=multiprocessing.cpu_count()withconcurrent.futures.ThreadPoolExecutor(max_workers=max_workers)asexecutor:results=list(executor.map(func,data))returnresults@staticmethoddefprocess_pool_processing(data:List[Any],func:Callable,max_workers:int=None)->List[Any]:"""Process pool for CPU-intensive tasks"""ifmax_workersisNone:max_workers=multiprocessing.cpu_count()withconcurrent.futures.ProcessPoolExecutor(max_workers=max_workers)asexecutor:results=list(executor.map(func,data))returnresults@staticmethodasyncdefasync_processing(data:List[Any],func:Callable)->List[Any]:"""Async processing for I/O-intensive tasks"""tasks=[func(item)foritemindata]results=awaitasyncio.gather(*tasks)returnresults@staticmethoddefbatch_processing(data:List[Any],func:Callable,batch_size:int=100)->List[Any]:"""Process data in batches"""results=[]foriinrange(0,len(data),batch_size):batch=data[i:i+batch_size]batch_results=[func(item)foriteminbatch]results.extend(batch_results)returnresultsclassAsyncOptimizer:"""Async optimization patterns"""@staticmethodasyncdefasync_generator(data:List[Any],func:Callable):"""Async generator for memory efficiency"""foritemindata:result=awaitfunc(item)yieldresult@staticmethodasyncdefasync_batch_processing(data:List[Any],func:Callable,batch_size:int=100):"""Async batch processing"""results=[]foriinrange(0,len(data),batch_size):batch=data[i:i+batch_size]batch_tasks=[func(item)foriteminbatch]batch_results=awaitasyncio.gather(*batch_tasks)results.extend(batch_results)returnresults@staticmethodasyncdefasync_with_semaphore(data:List[Any],func:Callable,max_concurrent:int=10):"""Async processing with semaphore for rate limiting"""semaphore=asyncio.Semaphore(max_concurrent)asyncdeflimited_func(item):asyncwithsemaphore:returnawaitfunc(item)tasks=[limited_func(item)foritemindata]results=awaitasyncio.gather(*tasks)returnresults# Performance comparisondefcpu_intensive_task(n:int)->int:"""CPU-intensive task"""returnsum(i*iforiinrange(n))defio_intensive_task(delay:float)->str:"""I/O-intensive task"""time.sleep(delay)returnf"Task completed after {delay}s"asyncdefasync_io_task(delay:float)->str:"""Async I/O-intensive task"""awaitasyncio.sleep(delay)returnf"Async task completed after {delay}s"defcompare_concurrency_methods():"""Compare different concurrency methods"""data=list(range(100))# Sequential processingstart_time=time.time()sequential_results=[cpu_intensive_task(i)foriindata]sequential_time=time.time()-start_time# Thread pool processingstart_time=time.time()thread_results=ConcurrencyOptimizer.parallel_processing(data,cpu_intensive_task)thread_time=time.time()-start_time# Process pool processingstart_time=time.time()process_results=ConcurrencyOptimizer.process_pool_processing(data,cpu_intensive_task)process_time=time.time()-start_timeprint(f"Sequential: {sequential_time:.4f}s")print(f"Thread pool: {thread_time:.4f}s")print(f"Process pool: {process_time:.4f}s")print(f"Thread speedup: {sequential_time/thread_time:.2f}x")print(f"Process speedup: {sequential_time/process_time:.2f}x")
# 1. Profile your codefrompython.profilingimportPerformanceProfilerprofiler=PerformanceProfiler()@profiler.profile_functiondefyour_function():# Your code herepass# 2. Benchmark different approachesfrompython.benchmarkingimportBenchmarkSuitebenchmark=BenchmarkSuite()benchmark.benchmark_function("approach1",function1)benchmark.benchmark_function("approach2",function2)# 3. Optimize memory usagefrompython.memory_optimizationimportMemoryOptimizeroptimizer=MemoryOptimizer()optimized_data=optimizer.memory_efficient_processing(data)# 4. Use concurrency for I/O-bound tasksfrompython.concurrencyimportConcurrencyOptimizerresults=ConcurrencyOptimizer.parallel_processing(data,your_function)