manual and readme update

This commit is contained in:
VALLONGOL 2025-06-23 14:42:47 +02:00
parent 21860078ce
commit 574c572110
3 changed files with 333 additions and 157 deletions

190
README.md
View File

@ -3,7 +3,9 @@
```markdown
# Python Profile Analyzer
Un'applicazione desktop GUI, cross-platform, per l'analisi visuale e interattiva dei dati di profiling `cProfile` di Python. Scritta in Python con Tkinter, questo strumento aiuta gli sviluppatori a identificare i colli di bottiglia nelle performance del loro codice in modo intuitivo e veloce.
**Un analizzatore di performance visuale e interattivo per Python.**
Python Profile Analyzer è un'applicazione desktop che aiuta gli sviluppatori a identificare i colli di bottiglia nel codice Python. Trasforma l'output testuale del profiler `cProfile` in viste interattive, rendendo l'ottimizzazione più rapida e intuitiva.
![Screenshot dell'applicazione](screenshot.png)
*(Nota: Sostituisci `screenshot.png` con uno screenshot reale dell'applicazione)*
@ -12,88 +14,62 @@ Un'applicazione desktop GUI, cross-platform, per l'analisi visuale e interattiva
## Caratteristiche Principali
* **Esecuzione e Profiling Integrati**: Esegui il profiling di script o moduli Python direttamente dall'applicazione attraverso un gestore di profili di lancio facile da usare.
* **Viste Multiple e Interattive**: Analizza i dati attraverso diverse prospettive:
* **Vista Tabellare**: Una tabella dettagliata con i dati di `pstats`, ordinabile dinamicamente per colonna (numero di chiamate, tempo totale, tempo cumulativo, ecc.).
* **Vista Testuale**: L'output standard di `pstats` per un'analisi classica.
* **Vista a Grafo**: Una visualizzazione a grafo delle chiamate (call graph) generata con Graphviz per identificare visivamente i percorsi più "costosi".
* **Filtraggio Dinamico**: Cerca e isola rapidamente funzioni specifiche nella vista tabellare e testuale.
* **Analisi Dettagliata Callers/Callees**: Seleziona una funzione per vedere istantaneamente quali altre funzioni l'hanno chiamata (callers) e quali funzioni ha chiamato (callees).
* **Visualizzazione a Grafo Intelligente**: Il grafo delle chiamate usa un codice colore (da verde a rosso) per evidenziare le funzioni che consumano più tempo, rendendo i colli di bottiglia immediatamente evidenti. La soglia di visualizzazione è regolabile.
* **Gestione Profili di Lancio**: Salva e gestisci diverse configurazioni di esecuzione (percorso dello script, argomenti, interprete Python, ecc.) per riutilizzarle facilmente.
* **Esportazione Dati**: Esporta la vista tabellare (filtrata e ordinata) in un file CSV per analisi esterne o reportistica.
* **Analisi Multi-Vista**: Esamina i dati attraverso una **tabella ordinabile**, una vista testuale e un **grafo delle chiamate** (call graph) con codice colore per evidenziare le funzioni più lente.
* **Esecuzione Integrata**: Configura ed esegui il profiling di script o moduli direttamente dall'applicazione.
* **Navigazione Interattiva**: Seleziona una funzione per scoprire istantaneamente chi la chiama (**Callers**) e cosa chiama (**Callees**).
* **Filtro Rapido**: Isola le funzioni di interesse con una ricerca testuale in tempo reale.
* **Esportazione CSV**: Salva i dati per analisi o reportistica esterna.
---
## Requisiti e Installazione
## Installazione Rapida
### 1. Clonare il Repository
```bash
git clone <URL_DEL_TUO_REPOSITORY_GITEA>
cd <NOME_DELLA_CARTELLA>
```
### 2. Dipendenze Python
È consigliabile creare un ambiente virtuale.
```bash
python -m venv venv
source venv/bin/activate # Su Windows: venv\Scripts\activate
```
Installa le librerie Python necessarie:
```bash
pip install -r requirements.txt
```
Il file `requirements.txt` dovrebbe contenere:
```
graphviz
Pillow
```
### 3. Dipendenza Esterna: Graphviz
La **Vista a Grafo** richiede che il software **Graphviz** sia installato sul tuo sistema e che il suo eseguibile sia presente nel PATH. La libreria Python da sola non è sufficiente.
* **Linux (Debian/Ubuntu)**:
1. **Clona il repository**:
```bash
sudo apt-get update
sudo apt-get install graphviz
git clone <URL_DEL_TUO_REPOSITORY_GITEA>
cd <NOME_DELLA_CARTELLA>
```
* **macOS (usando Homebrew)**:
```bash
brew install graphviz
```
* **Windows**:
1. Scarica l'installer dal [sito ufficiale di Graphviz](https://graphviz.org/download/).
2. Durante l'installazione, assicurati di selezionare l'opzione "Add Graphviz to the system PATH" (Aggiungi Graphviz al PATH di sistema).
> **Nota**: Se Graphviz non è installato, l'applicazione funzionerà comunque, ma la scheda "Graph View" sarà disabilitata.
2. **Crea un ambiente virtuale e installa le dipendenze**:
```bash
# Crea e attiva l'ambiente virtuale
python -m venv venv
source venv/bin/activate # Su Windows: venv\Scripts\activate
# Installa le librerie
pip install graphviz Pillow
```
3. **Installa Graphviz** (Requisito per la Vista a Grafo):
Questa è una dipendenza di sistema, non solo una libreria Python. Visita il [sito ufficiale di Graphviz](https://graphviz.org/download/) per scaricare e installare il software adatto al tuo sistema operativo. **Assicurati di aggiungerlo al PATH di sistema durante l'installazione.**
---
## Utilizzo
## Avvio
Per avviare l'applicazione, esegui il modulo `profileanalyzer` dalla root del progetto:
Per lanciare l'applicazione, esegui il comando seguente dalla cartella principale del progetto:
```bash
python -m profileanalyzer
```
### Flusso di Lavoro Tipico
1. Clicca su **"Profile a Script..."** per aprire il Gestore Profili.
2. Crea un "New Profile", specifica il percorso dello script/modulo, gli argomenti e salva.
3. Seleziona il profilo creato e clicca su **"Run & Profile Selected"**.
4. L'applicazione eseguirà il tuo script e caricherà automaticamente i risultati del profiling.
5. Esplora i dati nelle viste **Table**, **Text** e **Graph**. Usa il filtro e l'ordinamento per analizzare i risultati.
6. In alternativa, usa **"Load Profile File..."** per analizzare un file `.prof` preesistente.
```
---
---
---
## Documentazione
Per una guida dettagliata all'utilizzo, esempi pratici e suggerimenti su come interpretare i risultati, consulta i manuali utente completi:
* [Manuale Utente (Italiano)](./USER_MANUAL_IT.md)
* [User Manual (English)](./USER_MANUAL_EN.md)
*(Nota: Assicurati che i nomi dei file (`USER_MANUAL_IT.md` e `USER_MANUAL_EN.md`) corrispondano a quelli che userai nel tuo repository)*
### Versione in Inglese (per `README.md`)
```markdown
# Python Profile Analyzer
A cross-platform GUI desktop application for visual and interactive analysis of Python's `cProfile` profiling data. Written in Python with Tkinter, this tool helps developers quickly and intuitively identify performance bottlenecks in their code.
**A visual and interactive performance profiler for Python.**
Python Profile Analyzer is a desktop application that helps developers identify bottlenecks in their Python code. It transforms the standard text output of the `cProfile` profiler into interactive views, making optimization faster and more intuitive.
![Application Screenshot](screenshot.png)
*(Note: Replace `screenshot.png` with an actual screenshot of the application)*
@ -102,75 +78,51 @@ A cross-platform GUI desktop application for visual and interactive analysis of
## Key Features
* **Integrated Profiling Runner**: Profile Python scripts or modules directly from the application through an easy-to-use launch profile manager.
* **Multiple Interactive Views**: Analyze data from different perspectives:
* **Table View**: A detailed table of `pstats` data, dynamically sortable by any column (call count, total time, cumulative time, etc.).
* **Text View**: The standard `pstats` text output for a classic analysis.
* **Graph View**: A call graph visualization generated with Graphviz to visually identify the most expensive execution paths.
* **Dynamic Filtering**: Quickly search and isolate specific functions in the table and text views.
* **Detailed Caller/Callee Analysis**: Select any function to instantly see which other functions called it (callers) and which functions it called (callees).
* **Intelligent Graph Visualization**: The call graph is heat-mapped with colors (from green to red) to highlight functions that consume the most time, making bottlenecks immediately apparent. The node visibility threshold is adjustable.
* **Launch Profile Manager**: Save and manage different launch configurations (script path, arguments, Python interpreter, etc.) for easy reuse.
* **Data Export**: Export the current table view (filtered and sorted) to a CSV file for external analysis or reporting.
* **Multi-View Analysis**: Examine your data through a **sortable table**, a raw text view, and a heat-mapped **call graph** that highlights the slowest functions.
* **Integrated Runner**: Configure and run the profiler on your scripts or modules directly from the application.
* **Interactive Navigation**: Select any function to instantly discover its **Callers** and **Callees**.
* **Quick Filter**: Isolate functions of interest with a real-time text search.
* **CSV Export**: Save your data for external analysis or reporting.
---
## Requirements and Installation
## Quick Installation
### 1. Clone the Repository
```bash
git clone <YOUR_GITEA_REPOSITORY_URL>
cd <PROJECT_FOLDER_NAME>
```
### 2. Python Dependencies
It is highly recommended to use a virtual environment.
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
Install the required Python libraries:
```bash
pip install -r requirements.txt
```
Your `requirements.txt` file should contain:
```
graphviz
Pillow
```
### 3. External Dependency: Graphviz
The **Graph View** feature requires the **Graphviz** software to be installed on your system and its executable to be in the system's PATH. The Python library alone is not sufficient.
* **Linux (Debian/Ubuntu)**:
1. **Clone the repository**:
```bash
sudo apt-get update
sudo apt-get install graphviz
git clone <YOUR_GITEA_REPOSITORY_URL>
cd <PROJECT_FOLDER_NAME>
```
* **macOS (using Homebrew)**:
```bash
brew install graphviz
```
* **Windows**:
1. Download the installer from the [official Graphviz website](https://graphviz.org/download/).
2. During installation, make sure to check the option "Add Graphviz to the system PATH".
> **Note**: If Graphviz is not installed, the application will still run, but the "Graph View" tab will be disabled.
2. **Create a virtual environment and install dependencies**:
```bash
# Create and activate the virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install libraries
pip install graphviz Pillow
```
3. **Install Graphviz** (Required for the Graph View):
This is a system dependency, not just a Python library. Visit the [official Graphviz website](https://graphviz.org/download/) to download and install the software for your operating system. **Make sure to add it to your system's PATH during installation.**
---
## Usage
## Getting Started
To launch the application, run the `profileanalyzer` module from the project's root directory:
To launch the application, run the following command from the project's root directory:
```bash
python -m profileanalyzer
```
### Typical Workflow
1. Click **"Profile a Script..."** to open the Launch Manager.
2. Create a "New Profile", specify the script/module path, arguments, and save it.
3. Select the created profile and click **"Run & Profile Selected"**.
4. The application will run your script and automatically load the profiling results.
5. Explore the data in the **Table**, **Text**, and **Graph** views. Use the filter and sort controls to analyze the results.
6. Alternatively, use **"Load Profile File..."** to analyze a pre-existing `.prof` file.
```
---
## Documentation
For a detailed guide on usage, practical examples, and tips on how to interpret the results, please refer to the full user manuals:
* [User Manual (English)](./USER_MANUAL_EN.md)
* [Manuale Utente (Italiano)](./USER_MANUAL_IT.md)
*(Note: Ensure the filenames (`USER_MANUAL_EN.md` and `USER_MANUAL_IT.md`) match those you will use in your repository)*

View File

@ -1,24 +1,135 @@
# ProfileAnalyzer - English Manual
## User Manual: Python Profile Analyzer (English)
## Introduction
Welcome to ProfileAnalyzer. This document provides an overview of how to install, use, and understand the project.
### 1. Introduction
## Installation
Describe the installation steps here. For example:
1. Clone the repository: `git clone <repository_url>`
2. Navigate to the project directory: `cd ProfileAnalyzer`
3. Install dependencies: `pip install -r requirements.txt` (if applicable)
Welcome to the Python Profile Analyzer! This tool is designed to answer one of the most common questions in software development: "Why is my code slow?"
## Usage
Explain how to run and use the application.
- To run the application: `python -m profileanalyzer`
- Command-line arguments (if any).
- GUI interaction (if any).
Python Profile Analyzer allows you to run your code under Python's standard profiler, `cProfile`, and analyze the results through an intuitive graphical interface. Instead of parsing complex text files, you can navigate the data, sort, filter, and visualize the interactions between functions to quickly identify bottlenecks and optimize your application's performance.
## Development
Information for developers contributing to the project.
- Code structure.
- How to run tests.
### 2. Interface Overview
## Troubleshooting
Common issues and their solutions.
The interface is divided into three main areas:
1. **Top Toolbar**:
* **Load Profile File...**: Loads a pre-existing profiling data file (`.prof`).
* **Profile a Script...**: Opens the Launch Profile Manager to configure and run the profiler on a new script or module.
* **Export to CSV...**: Exports the data currently displayed in the table to a CSV file.
* **Current Profile**: Displays the name of the currently loaded profile file.
2. **Main Statistics Panel**:
* This is a tabbed area that provides different views of the data:
* **Table View**: The primary view. An interactive table with statistics for each function.
* **Text View**: The standard text output from `pstats`, useful for a classic overview.
* **Graph View**: (Available only if Graphviz is installed) A call graph visualization.
* **Controls (below the tabs)**: Allow you to sort and filter the data displayed in the table and text views.
3. **Details Panel (at the bottom)**:
* When you select a function in the **Table View**, these two panels are automatically populated:
* **Callers**: Shows which functions called the selected function.
* **Callees**: Shows which functions were called by the selected function.
### 3. Core Workflows
#### A. Profiling a New Script
This is the most common way to get started.
1. Click **"Profile a Script..."**. This will open the "Launch Profile Manager" window.
2. Click **"New"** to create a new profile.
3. **Fill in the profile details**:
* **Profile Name**: A descriptive name (e.g., "My Test Script").
* **Run as Module**: Check this option if you want to launch a module (e.g., `python -m my_module`).
* **Script Path** (if not a module): Click `...` to select the `.py` file to run.
* **Project Root Folder** (if running as a module): Click `...` to select your project's root folder.
* **Module Name** (if running as a module): Enter the name of the module to launch (e.g., `my_module.main`).
* **Arguments**: Enter any arguments to pass to the script (e.g., `--input file.txt --verbose`).
4. Click **"Save Changes"**.
5. Your new profile will appear in the list on the left. Select it and click **"Run & Profile Selected"**.
6. The application will run your script in the background. When it's finished, the results will be automatically loaded and displayed.
#### B. Loading an Existing Profile File
If you already have a data file (`.prof`) generated previously (even from the command-line `cProfile`), you can analyze it.
1. Click **"Load Profile File..."**.
2. Select your `.prof` file from the dialog box.
3. The data will be loaded and displayed in the interface.
### 4. Analyzing Results: A Use Case
Understanding the data is key. Let's imagine we have the following script, `slow_script.py`, to analyze:
```python
# slow_script.py
import time
def utility_function(n):
# A fast function, but called many times
return n * 2
def expensive_calculation():
# An intrinsically slow function
print("Doing expensive calculation...")
time.sleep(2) # Simulate a heavy computation
print("...done.")
def process_data():
# A function that orchestrates other calls
print("Processing data...")
total = 0
for i in range(1000):
total += utility_function(i)
expensive_calculation()
print(f"Final total: {total}")
if __name__ == "__main__":
process_data()
```
After profiling this script, here is how to interpret the results.
#### Step 1: What is the single slowest function?
Go to the **Table View** and click the **"Total Time (s)"** column header to sort in descending order.
* **What to look for**: The function at the top of the list. `Total Time` (or `tottime`) is the time spent *inside* a function, excluding time spent in functions it calls.
* **Expected Result**: You will see `time.sleep` or a similar function at the top, with a `tottime` of about 2 seconds. Right after it, you'll see `expensive_calculation`, but with a very low `tottime`, because almost all of its time was spent in `time.sleep`. This tells you that `expensive_calculation` is slow due to a specific operation within it.
#### Step 2: Which function is a bottleneck because of the functions it calls?
Now, sort by **"Cum. Time (s)"** (Cumulative Time).
* **What to look for**: `Cumulative Time` (or `cumtime`) is the total time spent in a function, *including* the time spent in all sub-calls. It's useful for finding "manager" functions that are slow because of the work they delegate.
* **Expected Result**: `process_data` will be at the top of the list with a `cumtime` of just over 2 seconds. Its `tottime` will be low, but the high `cumtime` tells us it's the starting point of our bottleneck.
#### Step 3: Is there a function that is called too many times?
Sort by **"N-Calls"** (Number of Calls).
* **What to look for**: Functions with an exceptionally high call count. Even a fast function, if called millions of times, can cause a slowdown due to overhead.
* **Expected Result**: `utility_function` will appear at the top with 1000 calls. By selecting it, you'll see its `tottime` and `cumtime` are very low, so in this case, it's not a problem. But if they were significant, you would have found a candidate for optimization (e.g., vectorization).
#### Step 4: How can I visualize the execution flow?
Switch to the **Graph View** tab.
* **What to look for**: The "hot path." The nodes (functions) are colored from green (fast) to red (slow) based on their `tottime`. The arrows indicate the call flow.
* **Expected Result**: You will see a path from `process_data` to `expensive_calculation`, and from there to `time.sleep`. The `time.sleep` node will be bright red, clearly indicating it's the source of the slowdown. You will also see an arrow from `process_data` to `utility_function` with the label "1000 calls".
* **Tip**: Use the **"Node Threshold"** slider to filter out insignificant functions and reduce noise in complex graphs.
#### Step 5: Who calls this slow function, and what does it call?
Return to the **Table View** and select the row for `expensive_calculation`.
* **Look at the Callers panel**: You will see that it was called by `process_data`.
* **Look at the Callees panel**: You will see that it called `time.sleep`.
This confirms the call context, helping you understand where and why a function is executed.
### 5. Troubleshooting
* **The "Graph View" is disabled or gray**:
1. Ensure you have installed the **Graphviz** software (not just the Python library).
2. Ensure that the Graphviz `bin` folder is in your system's `PATH`.
3. Ensure you have installed the `Pillow` library (`pip install Pillow`).
4. After loading a profile, an initial graph is generated automatically. If you don't see anything, try clicking "Generate Graph" or reducing the threshold.

View File

@ -1,24 +1,137 @@
# ProfileAnalyzer - Manuale Italiano
## Manuale Utente: Python Profile Analyzer (Italiano)
## Introduzione
Benvenuto in ProfileAnalyzer. Questo documento fornisce una panoramica su come installare, utilizzare e comprendere il progetto.
### 1. Introduzione
## Installazione
Descrivi i passaggi di installazione qui. Ad esempio:
1. Clona il repository: `git clone <repository_url>`
2. Naviga nella directory del progetto: `cd ProfileAnalyzer`
3. Installa le dipendenze: `pip install -r requirements.txt` (se applicabile)
Benvenuto in Python Profile Analyzer! Questo strumento è progettato per rispondere a una delle domande più comuni nello sviluppo software: "Perché il mio codice è lento?".
## Utilizzo
Spiega come eseguire e utilizzare l'applicazione.
- Per eseguire l'applicazione: `python -m profileanalyzer`
- Argomenti da riga di comando (se presenti).
- Interazione con la GUI (se presente).
Python Profile Analyzer ti permette di eseguire il tuo codice sotto il profiler standard di Python, `cProfile`, e di analizzare i risultati attraverso un'interfaccia grafica intuitiva. Invece di leggere file di testo complessi, potrai navigare tra i dati, ordinare, filtrare e visualizzare le interazioni tra le funzioni per identificare rapidamente i colli di bottiglia e ottimizzare le performance della tua applicazione.
### 2. Panoramica dell'Interfaccia
L'interfaccia è divisa in tre aree principali:
1. **Barra degli Strumenti Superiore**:
* **Load Profile File...**: Carica un file di dati di profiling (`.prof`) già esistente.
* **Profile a Script...**: Apre il Gestore Profili per configurare ed eseguire il profiling di un nuovo script o modulo.
* **Export to CSV...**: Esporta i dati attualmente visualizzati nella tabella in un file CSV.
* **Current Profile**: Mostra il nome del file di profilo attualmente caricato.
2. **Pannello delle Statistiche Principali**:
* È un'area a schede (tab) che fornisce diverse viste sui dati:
* **Table View**: La vista principale. Una tabella interattiva con le statistiche di ogni funzione.
* **Text View**: L'output testuale standard di `pstats`, utile per una visione d'insieme.
* **Graph View**: (Disponibile solo se Graphviz è installato) Una visualizzazione a grafo delle chiamate.
* **Controlli (sotto le schede)**: Permettono di ordinare e filtrare i dati visualizzati nella tabella e nella vista testuale.
3. **Pannello dei Dettagli (in basso)**:
* Quando selezioni una funzione nella **Table View**, questi due pannelli si popolano automaticamente:
* **Callers**: Mostra quali funzioni hanno chiamato la funzione selezionata.
* **Callees**: Mostra quali funzioni sono state chiamate dalla funzione selezionata.
### 3. Flussi di Lavoro Principali
#### A. Eseguire il Profiling di un Nuovo Script
Questo è il modo più comune per iniziare.
1. Clicca su **"Profile a Script..."**. Si aprirà la finestra "Launch Profile Manager".
2. Clicca su **"New"** per creare un nuovo profilo.
3. **Compila i dettagli del profilo**:
* **Profile Name**: Un nome descrittivo (es. "Mio Script di Test").
* **Run as Module**: Seleziona questa opzione se vuoi lanciare un modulo (es. `python -m mio_modulo`).
* **Script Path** (se non è un modulo): Clicca `...` per selezionare il file `.py` da eseguire.
* **Project Root Folder** (se è un modulo): Clicca `...` per selezionare la cartella radice del tuo progetto.
* **Module Name** (se è un modulo): Inserisci il nome del modulo da lanciare (es. `mio_modulo.main`).
* **Arguments**: Inserisci eventuali argomenti da passare allo script (es. `--input file.txt --verbose`).
4. Clicca su **"Save Changes"**.
5. Il tuo nuovo profilo apparirà nella lista a sinistra. Selezionalo e clicca **"Run & Profile Selected"**.
6. L'applicazione eseguirà lo script in background. Al termine, i risultati verranno automaticamente caricati e visualizzati.
#### B. Caricare un File di Profilo Esistente
Se hai già un file di dati (`.prof`) generato in precedenza (anche da `cProfile` da riga di comando), puoi analizzarlo.
1. Clicca su **"Load Profile File..."**.
2. Seleziona il tuo file `.prof` dalla finestra di dialogo.
3. I dati verranno caricati e visualizzati nell'interfaccia.
### 4. Analisi dei Risultati: Un Caso d'Uso
Comprendere i dati è la chiave. Immaginiamo di avere il seguente script `slow_script.py` da analizzare:
```python
# slow_script.py
import time
def utility_function(n):
# Funzione veloce, ma chiamata molte volte
return n * 2
def expensive_calculation():
# Funzione intrinsecamente lenta
print("Doing expensive calculation...")
time.sleep(2) # Simula un calcolo pesante
print("...done.")
def process_data():
# Funzione che orchestra altre chiamate
print("Processing data...")
total = 0
for i in range(1000):
total += utility_function(i)
expensive_calculation()
print(f"Final total: {total}")
if __name__ == "__main__":
process_data()
```
Dopo aver eseguito il profiling di questo script, ecco come interpretare i risultati.
#### Passo 1: Qual è la funzione più lenta in assoluto?
Vai alla **Table View** e clicca sull'header della colonna **"Total Time (s)"** per ordinare in modo decrescente.
* **Cosa cercare**: La funzione in cima alla lista. `Total Time` (o `tottime`) è il tempo speso *all'interno* di una funzione, escludendo il tempo speso nelle funzioni che essa chiama.
* **Risultato Atteso**: Vedrai `time.sleep` o una funzione simile in cima, con un `tottime` di circa 2 secondi. Subito dopo, vedrai `expensive_calculation`, ma con un `tottime` molto basso, perché quasi tutto il suo tempo è stato speso in `time.sleep`. Questo ti dice che `expensive_calculation` è lenta a causa di una specifica operazione al suo interno.
#### Passo 2: Quale funzione è un collo di bottiglia a causa delle funzioni che chiama?
Ora, ordina per **"Cum. Time (s)"** (Tempo Cumulativo).
* **Cosa cercare**: `Cumulative Time` (o `cumtime`) è il tempo totale speso in una funzione, *incluso* il tempo speso in tutte le sotto-chiamate. È utile per trovare le funzioni "manager" che sono lente a causa del lavoro che delegano.
* **Risultato Atteso**: `process_data` sarà in cima alla lista con un `cumtime` di poco superiore a 2 secondi. Il suo `tottime` sarà basso, ma il `cumtime` alto ci dice che è il punto di partenza del nostro collo di bottiglia.
#### Passo 3: C'è una funzione che viene chiamata troppe volte?
Ordina per **"N-Calls"** (Numero di Chiamate).
* **Cosa cercare**: Funzioni con un numero di chiamate eccezionalmente alto. Anche una funzione veloce, se chiamata milioni di volte, può causare un rallentamento a causa dell'overhead.
* **Risultato Atteso**: `utility_function` apparirà in cima con 1000 chiamate. Selezionandola, vedrai che il suo `tottime` e `cumtime` sono molto bassi, quindi in questo caso non è un problema. Ma se lo fossero, avresti trovato un candidato per l'ottimizzazione (es. vettorizzazione).
#### Passo 4: Come posso visualizzare il flusso di esecuzione?
Passa alla scheda **Graph View**.
* **Cosa cercare**: Il "percorso caldo" (hot path). I nodi (funzioni) sono colorati da verde (veloce) a rosso (lento) in base al loro `tottime`. Le frecce indicano il flusso delle chiamate.
* **Risultato Atteso**: Vedrai un percorso che va da `process_data` a `expensive_calculation`, e da lì a `time.sleep`. Il nodo `time.sleep` sarà rosso vivo, indicando chiaramente che è la fonte del rallentamento. Vedrai anche una freccia da `process_data` a `utility_function` con l'etichetta "1000 calls".
* **Consiglio**: Usa lo slider **"Node Threshold"** per filtrare le funzioni poco significative e ridurre il rumore nei grafi complessi.
#### Passo 5: Chi chiama questa funzione lenta e cosa chiama?
Torna alla **Table View** e seleziona la riga di `expensive_calculation`.
* **Guarda il pannello Callers**: Vedrai che è stata chiamata da `process_data`.
* **Guarda il pannello Callees**: Vedrai che ha chiamato `time.sleep`.
Questo conferma il contesto della chiamata, aiutandoti a capire dove e perché una funzione viene eseguita.
### 5. Risoluzione dei Problemi
* **La "Graph View" è disabilitata o grigia**:
1. Assicurati di aver installato il software **Graphviz** (non solo la libreria Python).
2. Assicurati che la cartella `bin` di Graphviz sia nel `PATH` del tuo sistema.
3. Assicurati di aver installato la libreria `Pillow` (`pip install Pillow`).
4. Dopo aver caricato un profilo, un grafo iniziale viene generato automaticamente. Se non vedi nulla, prova a cliccare "Generate Graph" o a ridurre la soglia.
## Sviluppo
Informazioni per gli sviluppatori che contribuiscono al progetto.
- Struttura del codice.
- Come eseguire i test.
## Risoluzione dei problemi
Problemi comuni e relative soluzioni.