Skip to main content
Learn how to identify and resolve performance issues with your sandbox operations.

Identify Performance Bottlenecks

Monitor sandbox performance to identify bottlenecks:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox
import time

def monitor_performance(sandbox: Sandbox, code: str):
    """Monitor code execution performance"""
    start_time = time.time()
    
    result = sandbox.run_code(code)
    
    execution_time = time.time() - start_time
    
    # Get metrics
    metrics = sandbox.get_metrics()
    
    return {
        "execution_time": execution_time,
        "cpu_percent": metrics.cpu_percent,
        "memory_used_mb": metrics.memory_used_mb,
        "memory_total_mb": metrics.memory_total_mb,
        "code_success": result.success
    }

with Sandbox.create(template="code-interpreter") as sandbox:
    perf = monitor_performance(sandbox, """
import pandas as pd
df = pd.DataFrame({'a': range(100000)})
result = df['a'].sum()
    """)
    
    print(f"Execution time: {perf['execution_time']:.2f}s")
    print(f"CPU usage: {perf['cpu_percent']}%")
    print(f"Memory usage: {perf['memory_used_mb']}/{perf['memory_total_mb']} MB")
    
    # Identify bottlenecks
    if perf['execution_time'] > 10:
        print("⚠️  Slow execution - consider optimizing code")
    if perf['cpu_percent'] > 80:
        print("⚠️  High CPU usage - consider more vCPUs")
    if perf['memory_used_mb'] / perf['memory_total_mb'] > 0.9:
        print("⚠️  High memory usage - consider more RAM")

Optimize Resource Usage

Right-size resources based on actual usage:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox

def optimize_resources(workload_type: str):
    """Get optimal resources for workload type"""
    resource_map = {
        "lightweight": {"vcpu": 1, "memory_mb": 512, "disk_gb": 5},
        "data_analysis": {"vcpu": 4, "memory_mb": 4096, "disk_gb": 20},
        "ml_training": {"vcpu": 16, "memory_mb": 16384, "disk_gb": 100}
    }
    
    return resource_map.get(workload_type, resource_map["lightweight"])

# Use optimized resources
resources = optimize_resources("data_analysis")
sandbox = Sandbox.create(
    template="code-interpreter",
    **resources
)

Optimize Code Execution

Write efficient code for better performance:
  • Python
  • JavaScript/TypeScript
from hopx_ai import Sandbox

# ✅ Good: Vectorized operations
efficient_code = """
import pandas as pd
import numpy as np

# Fast: Vectorized operations
df = pd.DataFrame({'a': range(1000000)})
df['b'] = df['a'] * 2  # Vectorized
result = df['a'].sum()  # Vectorized
"""

# ❌ Bad: Python loops
# inefficient_code = """
# result = 0
# for i in range(1000000):
#     result += i  # Slow: Python loop
# """

with Sandbox.create(template="code-interpreter") as sandbox:
    result = sandbox.run_code(efficient_code)

Common Performance Issues

Symptoms: Code takes too long to executeSolutions:
  • Use vectorized operations (NumPy, Pandas)
  • Avoid Python loops for large datasets
  • Break long operations into smaller chunks
  • Increase timeout if needed
Symptoms: CPU usage consistently above 80%Solutions:
  • Increase vCPU count
  • Optimize code to use less CPU
  • Use parallel processing
  • Profile code to find bottlenecks
Symptoms: Memory usage above 90%Solutions:
  • Increase memory allocation
  • Process data in chunks
  • Delete unused variables
  • Use generators instead of lists
Symptoms: Sandbox creation takes too longSolutions:
  • Use pre-built templates
  • Reuse sandboxes when possible
  • Check network connectivity
  • Use closer regions

Performance Optimization Checklist

  • Use vectorized operations
  • Avoid unnecessary loops
  • Process data in chunks
  • Delete unused variables
  • Right-size resources
  • Monitor resource usage
  • Adjust based on metrics
  • Use appropriate templates
  • Reuse sandboxes
  • Run operations in parallel
  • Set appropriate timeouts
  • Batch operations

Next Steps