Buckets:

download
raw
11.7 kB
"""
Benchmark memory usage for Zen-AI-Pentest
This module benchmarks memory usage during various operations.
"""
import gc
import json
import os
import sys
import time
import tracemalloc
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, List
import psutil
# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@dataclass
class MemorySnapshot:
"""Memory usage snapshot"""
rss_mb: float
vms_mb: float
percent: float
traced_mb: float = 0.0
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
def to_dict(self) -> Dict:
return {
"rss_mb": self.rss_mb,
"vms_mb": self.vms_mb,
"percent": self.percent,
"traced_mb": self.traced_mb,
"timestamp": self.timestamp,
}
@dataclass
class MemoryBenchmarkResult:
"""Result of memory benchmark"""
operation: str
before: MemorySnapshot
after: MemorySnapshot
peak: MemorySnapshot
delta_rss_mb: float
delta_vms_mb: float
duration: float
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict:
return {
"operation": self.operation,
"before": self.before.to_dict(),
"after": self.after.to_dict(),
"peak": self.peak.to_dict(),
"delta_rss_mb": self.delta_rss_mb,
"delta_vms_mb": self.delta_vms_mb,
"duration": self.duration,
"timestamp": self.timestamp,
"metadata": self.metadata,
}
class MemoryBenchmark:
"""Benchmark memory usage"""
def __init__(self):
self.process = psutil.Process(os.getpid())
self.results: List[MemoryBenchmarkResult] = []
self.tracing = False
def get_memory_usage(self) -> MemorySnapshot:
"""Get current memory usage"""
mem = self.process.memory_info()
percent = self.process.memory_percent()
traced_mb = 0
if self.tracing and tracemalloc.is_tracing():
current, peak = tracemalloc.get_traced_memory()
traced_mb = current / 1024 / 1024
return MemorySnapshot(
rss_mb=mem.rss / 1024 / 1024,
vms_mb=mem.vms / 1024 / 1024,
percent=percent,
traced_mb=traced_mb,
)
def start_tracing(self):
"""Start tracemalloc for detailed memory tracking"""
tracemalloc.start()
self.tracing = True
def stop_tracing(self):
"""Stop tracemalloc"""
if self.tracing:
tracemalloc.stop()
self.tracing = False
def benchmark_operation(
self,
operation_name: str,
operation_func,
*args,
**kwargs,
) -> MemoryBenchmarkResult:
"""Benchmark memory usage for an operation"""
# Force garbage collection before measurement
gc.collect()
time.sleep(0.1)
before = self.get_memory_usage()
start_time = time.time()
# Start peak tracking
if not self.tracing:
self.start_tracing()
try:
result = operation_func(*args, **kwargs)
except Exception as e:
print(f" Error in {operation_name}: {e}")
result = None
elapsed = time.time() - start_time
# Get peak memory
peak_mb = 0
if tracemalloc.is_tracing():
current, peak = tracemalloc.get_traced_memory()
peak_mb = peak / 1024 / 1024
after = self.get_memory_usage()
peak_snapshot = MemorySnapshot(
rss_mb=max(before.rss_mb, after.rss_mb),
vms_mb=max(before.vms_mb, after.vms_mb),
percent=max(before.percent, after.percent),
traced_mb=peak_mb,
)
result_obj = MemoryBenchmarkResult(
operation=operation_name,
before=before,
after=after,
peak=peak_snapshot,
delta_rss_mb=after.rss_mb - before.rss_mb,
delta_vms_mb=after.vms_mb - before.vms_mb,
duration=elapsed,
metadata={"result_type": type(result).__name__ if result else None},
)
self.results.append(result_obj)
return result_obj
def benchmark_tool_loading(self):
"""Benchmark memory used by loading tools"""
def load_tools():
from tools import (
ffuf_integration_enhanced,
httpx_integration,
nmap_integration,
subfinder_integration,
)
return {
"nmap": nmap_integration,
"httpx": httpx_integration,
"subfinder": subfinder_integration,
"ffuf": ffuf_integration_enhanced,
}
return self.benchmark_operation("Tool Module Loading", load_tools)
def benchmark_data_structures(self):
"""Benchmark memory for large data structures"""
def create_large_structure():
# Simulate scan results data structure
results = []
for i in range(1000):
results.append(
{
"id": i,
"target": f"target-{i}.example.com",
"ports": [80, 443, 8080, 8443],
"findings": [f"finding-{j}" for j in range(10)],
"metadata": {
"scan_time": time.time(),
"status": "completed",
},
}
)
return results
return self.benchmark_operation("Large Data Structure Creation", create_large_structure)
def benchmark_string_operations(self):
"""Benchmark memory for string operations"""
def string_operations():
# Simulate log processing
logs = []
for i in range(10000):
logs.append(f"Log entry {i}: " + "X" * 100)
return "\n".join(logs)
return self.benchmark_operation("String Processing", string_operations)
def benchmark_json_parsing(self):
"""Benchmark memory for JSON parsing"""
def parse_json():
# Simulate parsing large JSON response
data = {
"scan_id": "test-123",
"targets": [f"target-{i}.com" for i in range(100)],
"results": [
{
"host": f"host-{i}",
"ports": [{"port": p, "state": "open"} for p in range(1, 100)],
}
for i in range(50)
],
}
json_str = json.dumps(data)
return json.loads(json_str)
return self.benchmark_operation("JSON Parsing", parse_json)
def run_all_benchmarks(self) -> List[MemoryBenchmarkResult]:
"""Run all memory benchmarks"""
print(f"\n{'=' * 60}")
print("MEMORY USAGE BENCHMARK")
print(f"{'=' * 60}")
print(f"Process ID: {self.process.pid}")
print(f"{'=' * 60}\n")
operations = [
("Tool Module Loading", self.benchmark_tool_loading),
("Large Data Structures", self.benchmark_data_structures),
("String Processing", self.benchmark_string_operations),
("JSON Parsing", self.benchmark_json_parsing),
]
for name, func in operations:
print(f"Benchmarking: {name}...")
try:
result = func()
print(
f" ✓ Delta: {result.delta_rss_mb:+.2f} MB RSS, "
f"Peak: {result.peak.traced_mb:.2f} MB, "
f"Duration: {result.duration:.2f}s"
)
except Exception as e:
print(f" ✗ Failed: {e}")
self.stop_tracing()
return self.results
def generate_report(self) -> str:
"""Generate markdown report"""
report = "# Memory Usage Benchmark Report\n\n"
report += f"**Date:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
report += f"**Process ID:** {self.process.pid}\n\n"
report += "## Summary\n\n"
report += "| Operation | Delta RSS (MB) | Delta VMS (MB) | Peak (MB) | Duration (s) |\n"
report += "|-----------|----------------|----------------|-----------|-------------|\n"
for result in self.results:
report += (
f"| {result.operation} | {result.delta_rss_mb:+.2f} | "
f"{result.delta_vms_mb:+.2f} | {result.peak.traced_mb:.2f} | "
f"{result.duration:.2f} |\n"
)
report += "\n## Detailed Results\n\n"
for result in self.results:
report += f"### {result.operation}\n\n"
report += "**Before:**\n"
report += f"- RSS: {result.before.rss_mb:.2f} MB\n"
report += f"- VMS: {result.before.vms_mb:.2f} MB\n"
report += f"- Percent: {result.before.percent:.2f}%\n\n"
report += "**After:**\n"
report += f"- RSS: {result.after.rss_mb:.2f} MB\n"
report += f"- VMS: {result.after.vms_mb:.2f} MB\n"
report += f"- Percent: {result.after.percent:.2f}%\n\n"
report += "**Peak:**\n"
report += f"- Traced: {result.peak.traced_mb:.2f} MB\n\n"
report += "**Delta:**\n"
report += f"- RSS: {result.delta_rss_mb:+.2f} MB\n"
report += f"- VMS: {result.delta_vms_mb:+.2f} MB\n"
report += f"- Duration: {result.duration:.2f}s\n\n"
return report
def save_results(self, output_dir: str = "benchmarks/results"):
"""Save results to JSON file"""
os.makedirs(output_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filepath = os.path.join(output_dir, f"memory_usage_{timestamp}.json")
data = {
"timestamp": datetime.now().isoformat(),
"pid": self.process.pid,
"results": [r.to_dict() for r in self.results],
}
with open(filepath, "w") as f:
json.dump(data, f, indent=2)
print(f"\nResults saved to: {filepath}")
return filepath
def save_report(self, output_dir: str = "benchmarks/results"):
"""Save markdown report"""
os.makedirs(output_dir, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filepath = os.path.join(output_dir, f"memory_usage_{timestamp}.md")
with open(filepath, "w") as f:
f.write(self.generate_report())
print(f"Report saved to: {filepath}")
return filepath
# Run benchmark
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Memory Usage Benchmark")
parser.add_argument("--save", action="store_true", help="Save results to file")
args = parser.parse_args()
benchmark = MemoryBenchmark()
try:
results = benchmark.run_all_benchmarks()
print("\n" + benchmark.generate_report())
if args.save or input("\nSave results? (y/n): ").lower().strip() == "y":
benchmark.save_results()
benchmark.save_report()
except KeyboardInterrupt:
print("\n\nBenchmark interrupted by user.")
sys.exit(1)
except Exception as e:
print(f"\n\nBenchmark failed: {e}")
import traceback
traceback.print_exc()
sys.exit(1)

Xet Storage Details

Size:
11.7 kB
·
Xet hash:
3c386e59ba85606f21889cf4877a237ea3b34ac35992c63978ee00ded8bf9d6f

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.