From 24fd2cdb4fc2032512f03e472218e3d296af8671 Mon Sep 17 00:00:00 2001 From: Jimmy Royer Date: Wed, 2 Oct 2024 17:53:10 -0400 Subject: [PATCH] Added profiling code around library init --- application.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/application.py b/application.py index 401d8bf024..fa4ad43401 100644 --- a/application.py +++ b/application.py @@ -4,6 +4,21 @@ import os import time +# Check if profiling should be enabled +enable_profiling = os.getenv('NOTIFY_PROFILE') is not None + +if enable_profiling: + print("Profiling enabled") + import cProfile + import pstats + from pstats import SortKey + + # Create a cProfile.Profile object + profiler = cProfile.Profile() + # Start profiling + profiler.enable() + +# Timer start for initialization. start_time = time.time() import newrelic.agent # See https://bit.ly/2xBVKBH @@ -43,10 +58,22 @@ print("========================================================") print("") +# Timer end for initialization. end_time = time.time() elapsed_time = end_time - start_time print(f"Elapsed time: {elapsed_time:.2f}s") +if enable_profiling: + # Stop profiling + profiler.disable() + # Dump profiling results to a file + profiler.dump_stats('profile_results.prof') + # Analyze profiling results + with open('profile_report.txt', 'w') as f: + stats = pstats.Stats('profile_results.prof', stream=f) + stats.sort_stats(SortKey.CUMULATIVE) + stats.print_stats() + def handler(event, context): newrelic.agent.initialize() # noqa: E402 newrelic.agent.register_application(timeout=20.0)