Skip to content

Commit

Permalink
Add memory profiling and improve code formatting in asgi.py and core.py
Browse files Browse the repository at this point in the history
  • Loading branch information
DonnieBLT committed Jan 1, 2025
1 parent 7a24d04 commit 4cf8c2d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
3 changes: 3 additions & 0 deletions blt/asgi.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# asgi.py

import os
import tracemalloc

import django

Expand All @@ -12,6 +13,8 @@
from django.core.asgi import get_asgi_application
from django.urls import path

tracemalloc.start()

from website import consumers # You will define a consumer for handling WebSockets

application = ProtocolTypeRouter(
Expand Down
15 changes: 10 additions & 5 deletions website/views/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,19 +61,21 @@
# ----------------------------------------------------------------------------------


def memory_usage_by_module(limit=10):
def memory_usage_by_module(limit=100):
"""
Returns a list of (filename, size_in_bytes) for the top
`limit` files by allocated memory, using tracemalloc.
"""
tracemalloc.start()
# tracemalloc.start()
snapshot = tracemalloc.take_snapshot()
print("Memory snapshot taken. and it is: ", snapshot)

# Group memory usage by filename
stats = snapshot.statistics("filename")
module_usage = {}

for stat in stats:
print("stat is: ", stat)
if stat.traceback:
filename = stat.traceback[0].filename
# Accumulate memory usage
Expand Down Expand Up @@ -265,7 +267,7 @@ def check_status(request):
# Memory usage by module (via tracemalloc)
# -------------------------------------------------------
print("Calculating memory usage by module...")
top_modules = memory_usage_by_module(limit=10)
top_modules = memory_usage_by_module(limit=100)
status_data["memory_by_module"] = top_modules

# -------------------------------------------------------
Expand All @@ -281,8 +283,11 @@ def check_status(request):
# Redis stats
# -------------------------------------------------------
print("Getting Redis stats...")
redis_client = get_redis_connection("default")
status_data["redis_stats"] = redis_client.info()
try:
redis_client = get_redis_connection("default")
status_data["redis_stats"] = redis_client.info()
except Exception as e:
print(f"Redis error or not supported: {e}")

# -------------------------------------------------------
# Memory profiling info (current, peak) - optional
Expand Down

0 comments on commit 4cf8c2d

Please sign in to comment.