Skip to content

Instantly share code, notes, and snippets.

@asmattic
Created June 20, 2025 03:00
Show Gist options
  • Save asmattic/c04efff05c2c31c56af5b2087b0a11ec to your computer and use it in GitHub Desktop.
Save asmattic/c04efff05c2c31c56af5b2087b0a11ec to your computer and use it in GitHub Desktop.
Linux VM or Native Python script for a quick gauge of system performance capabilities
import psutil
import time
import datetime
import csv
import os
# --- Configuration ---
LOG_INTERVAL_SECONDS = 5 # How often to log data (in seconds)
LOG_DURATION_MINUTES = 60 # How long to run the monitoring (in minutes). Set to 0 for indefinite.
LOG_FILE_NAME = "system_performance_log.csv"
CSV_HEADER = ["Timestamp", "CPU Usage (%)", "Memory Usage (%)", "Available Memory (MB)", "Used Memory (MB)"]
def get_system_stats():
"""
Retrieves current CPU and memory statistics.
"""
cpu_usage = psutil.cpu_percent(interval=None) # interval=None gets instantaneous usage
memory_info = psutil.virtual_memory()
memory_usage_percent = memory_info.percent
available_memory_mb = memory_info.available / (1024 * 1024) # Convert bytes to MB
used_memory_mb = memory_info.used / (1024 * 1024) # Convert bytes to MB
return cpu_usage, memory_usage_percent, available_memory_mb, used_memory_mb
def write_log_header(file_path):
"""
Writes the CSV header if the log file doesn't exist or is empty.
"""
file_exists = os.path.isfile(file_path)
is_empty = os.path.getsize(file_path) == 0 if file_exists else True
if not file_exists or is_empty:
with open(file_path, 'w', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow(CSV_HEADER)
print(f"Log file '{file_path}' created with header.")
def log_system_stats(file_path, stats):
"""
Appends system statistics to the log file.
"""
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = [timestamp] + list(stats)
try:
with open(file_path, 'a', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow(log_entry)
except IOError as e:
print(f"Error writing to log file: {e}")
def main():
"""
Main function to run the system performance monitor.
"""
print("Starting System Performance Monitor...")
print(f"Logging data every {LOG_INTERVAL_SECONDS} seconds.")
if LOG_DURATION_MINUTES > 0:
print(f"Monitoring will run for {LOG_DURATION_MINUTES} minutes.")
end_time = time.time() + LOG_DURATION_MINUTES * 60
else:
print("Monitoring will run indefinitely. Press Ctrl+C to stop.")
end_time = float('inf') # Run indefinitely
# Ensure log file has a header
write_log_header(LOG_FILE_NAME)
try:
while time.time() < end_time:
# Get current stats
cpu_percent, mem_percent, mem_available_mb, mem_used_mb = get_system_stats()
# Log the stats
log_system_stats(LOG_FILE_NAME, (cpu_percent, mem_percent, mem_available_mb, mem_used_mb))
# Print to console (optional)
print(f"{datetime.datetime.now().strftime('%H:%M:%S')} - CPU: {cpu_percent:5.1f}%, Memory: {mem_percent:5.1f}% ({mem_used_mb:.2f}MB Used / {mem_available_mb:.2f}MB Avail)")
# Wait for the next interval
time.sleep(LOG_INTERVAL_SECONDS)
except KeyboardInterrupt:
print("\nMonitoring stopped by user.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
print(f"Performance logs saved to '{LOG_FILE_NAME}'")
print("Exiting System Performance Monitor.")
if __name__ == "__main__":
# Before running, ensure you have psutil installed:
# pip install psutil
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment