Wednesday, February 14, 2024

Capture Server stats during the load test using python

Code Block with Copy Button
    
      # Python code to capture server stats during load test
      import psutil
      import time
      import matplotlib.pyplot as plt
      
      # Function to capture and plot server stats
      def capture_server_stats(duration, interval):
          timestamps = []
          cpu_percentages = []
          memory_percentages = []
      
          end_time = time.time() + duration
      
          while time.time() < end_time:
              # Capture CPU and memory usage
              cpu_percent = psutil.cpu_percent(interval=interval)
              memory_percent = psutil.virtual_memory().percent
      
              # Record timestamp and stats
              timestamps.append(time.time())
              cpu_percentages.append(cpu_percent)
              memory_percentages.append(memory_percent)
      
              # Print stats (optional)
              print(f"CPU Usage: {cpu_percent}% | Memory Usage: {memory_percent}%")
      
              # Sleep for the specified interval
              time.sleep(interval)
      
          # Plot the data
          plt.figure(figsize=(10, 5))
          plt.plot(timestamps, cpu_percentages, label='CPU Usage (%)', color='blue')
          plt.plot(timestamps, memory_percentages, label='Memory Usage (%)', color='green')
          plt.xlabel('Time (seconds)')
          plt.ylabel('Usage (%)')
          plt.title('Server Stats During Load Test')
          plt.legend()
          plt.grid(True)
          plt.show()
      
      # Example usage: Capture server stats for 60 seconds with an interval of 1 second
      capture_server_stats(duration=60, interval=1)
    
  

psutil library is used to capture CPU and memory usage statistics.

capture_server_stats function captures CPU and memory usage at regular intervals for the specified duration.

The captured data is stored in lists (timestamps, cpu_percentages, memory_percentages).

The data is then plotted using matplotlib.

No comments: