funcprofiler 1.0.2__tar.gz → 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: funcprofiler
3
- Version: 1.0.2
3
+ Version: 1.1.0
4
4
  Summary: An open-source Python library for finding bottlenecks in code. Includes function profiling, data exports, logging, and even line-by-line profiling, for more control.
5
5
  Home-page: https://github.com/infinitode/funcprofiler
6
6
  Author: Infinitode Pty Ltd
@@ -25,6 +25,7 @@ Dynamic: classifier
25
25
  Dynamic: description
26
26
  Dynamic: description-content-type
27
27
  Dynamic: home-page
28
+ Dynamic: license-file
28
29
  Dynamic: requires-python
29
30
  Dynamic: summary
30
31
 
@@ -37,8 +38,11 @@ Dynamic: summary
37
38
 
38
39
  An open-source Python library for identifying bottlenecks in code. It includes function profiling, data exports, logging, and line-by-line profiling for more granular control.
39
40
 
40
- ## Changelog (v.1.0.2):
41
- - Added support for 2 new export formats: `xml` and `md` in both function profiling, and line-by-line profiling.
41
+ ## Changelog (v.1.1.0):
42
+ - Added support for 2 new export formats: `yaml` and `toml`.
43
+ - Exports now include more information: peak memory usage, timestamp, arguments, return value, filepath, line number, and docstring.
44
+ - Added `enabled` and `log_level` options to the decorators.
45
+ - Improved export formats for better readability.
42
46
 
43
47
  ## Installation
44
48
 
@@ -50,25 +54,30 @@ pip install funcprofiler
50
54
 
51
55
  ## Supported Python Versions
52
56
 
53
- FuncProfiler supports the following Python versions:
54
-
55
- - Python 3.6
56
- - Python 3.7
57
- - Python 3.8
58
- - Python 3.9
59
- - Python 3.10
60
- - Python 3.11 and later (preferred)
61
-
62
- Please ensure that you have one of these Python versions installed. FuncProfiler may not function as expected on earlier versions.
57
+ FuncProfiler supports Python 3.6 and later.
63
58
 
64
59
  ## Features
65
60
 
66
- - **Function Profiling**: Monitor a function's memory usage and execution time to identify performance issues.
67
- - **Line-by-Line Profiling**: Return execution time and memory usage for each line of any given function.
68
- - **Shared Logging**: Log outputs of functions triggered by the line-by-line and function profilers, storing results in a `.txt` file.
69
- - **File Exports**: Export profiling data from functions in `csv`, `json`, `html`, `xml` and `md` formats, for both line-by-line profiling and function profiling.
70
- > [!NOTE]
71
- > View more export types in the [official documentation](https://infinitode-docs.gitbook.io/documentation/package-documentation/funcprofiler-package-documentation).
61
+ - **Function Profiling**: Monitor a function's memory usage and execution time.
62
+ - **Line-by-Line Profiling**: Get execution time and memory usage for each line of a function.
63
+ - **Shared Logging**: Log profiler outputs to a `.txt` file.
64
+ - **File Exports**: Export profiling data in various formats.
65
+ - **New Options**:
66
+ - `enabled`: A boolean to enable or disable profiling.
67
+ - `log_level`: Set the logging level to "info" or "debug".
68
+
69
+ ## Export Formats
70
+
71
+ | Format | `function_profile` | `line_by_line_profile` |
72
+ |--------|--------------------|------------------------|
73
+ | `txt` | ✅ | ❌ |
74
+ | `json` | ✅ | ✅ |
75
+ | `csv` | ✅ | ✅ |
76
+ | `html` | ✅ | ✅ |
77
+ | `xml` | ✅ | ✅ |
78
+ | `md` | ✅ | ✅ |
79
+ | `yaml` | ✅ | ✅ |
80
+ | `toml` | ✅ | ✅ |
72
81
 
73
82
  ## Usage
74
83
 
@@ -77,12 +86,10 @@ Please ensure that you have one of these Python versions installed. FuncProfiler
77
86
  ```python
78
87
  from funcprofiler import function_profile
79
88
 
80
- # Exporting as `html` with logging enabled
81
- @function_profile(export_format="html", shared_log=True)
89
+ @function_profile(export_format="html", shared_log=True, log_level="debug")
82
90
  def some_function():
83
91
  return "Hello World."
84
92
 
85
- # Call the function
86
93
  message = some_function()
87
94
  ```
88
95
 
@@ -91,28 +98,21 @@ message = some_function()
91
98
  ```python
92
99
  from funcprofiler import line_by_line_profile
93
100
 
94
- # Logging enabled without exports
95
- @line_by_line_profile(shared_log=True)
101
+ @line_by_line_profile(shared_log=True, enabled=True)
96
102
  def some_complicated_function(n):
97
103
  total = 0
98
104
  for i in range(n):
99
105
  for j in range(i):
100
- total += (i * j) ** 0.5 # Square root calculation
106
+ total += (i * j) ** 0.5
101
107
  return total
102
108
 
103
- # Call the function
104
109
  total = some_complicated_function(1000)
105
110
  ```
106
111
 
107
- > [!NOTE]
108
- > FuncProfiler can be added to any function using the callable format: `@funcprofiler_function_name(expected_arguments)`.
109
-
110
112
  ## Contributing
111
113
 
112
- Contributions are welcome! If you encounter issues, have suggestions, or wish to contribute to FuncProfiler, please open an issue or submit a pull request on [GitHub](https://github.com/infinitode/funcprofiler).
114
+ Contributions are welcome! Please open an issue or submit a pull request on [GitHub](https://github.com/infinitode/funcprofiler).
113
115
 
114
116
  ## License
115
117
 
116
- FuncProfiler is released under the terms of the **MIT License (Modified)**. Please see the [LICENSE](https://github.com/infinitode/funcprofiler/blob/main/LICENSE) file for the full text.
117
-
118
- **Modified License Clause**: The modified license clause allows users to create derivative works based on the FuncProfiler software. However, it requires that any substantial changes to the software be clearly distinguished from the original work and distributed under a different name.
118
+ FuncProfiler is released under the **MIT License (Modified)**. See the [LICENSE](https://github.com/infinitode/funcprofiler/blob/main/LICENSE) file for details.
@@ -0,0 +1,87 @@
1
+ # FuncProfiler
2
+ ![Python Version](https://img.shields.io/badge/python-3.13-blue.svg)
3
+ [![Code Size](https://img.shields.io/github/languages/code-size/infinitode/funcprofiler)](https://github.com/infinitode/funcprofiler)
4
+ ![Downloads](https://pepy.tech/badge/funcprofiler)
5
+ ![License Compliance](https://img.shields.io/badge/license-compliance-brightgreen.svg)
6
+ ![PyPI Version](https://img.shields.io/pypi/v/funcprofiler)
7
+
8
+ An open-source Python library for identifying bottlenecks in code. It includes function profiling, data exports, logging, and line-by-line profiling for more granular control.
9
+
10
+ ## Changelog (v.1.1.0):
11
+ - Added support for 2 new export formats: `yaml` and `toml`.
12
+ - Exports now include more information: peak memory usage, timestamp, arguments, return value, filepath, line number, and docstring.
13
+ - Added `enabled` and `log_level` options to the decorators.
14
+ - Improved export formats for better readability.
15
+
16
+ ## Installation
17
+
18
+ You can install FuncProfiler using pip:
19
+
20
+ ```bash
21
+ pip install funcprofiler
22
+ ```
23
+
24
+ ## Supported Python Versions
25
+
26
+ FuncProfiler supports Python 3.6 and later.
27
+
28
+ ## Features
29
+
30
+ - **Function Profiling**: Monitor a function's memory usage and execution time.
31
+ - **Line-by-Line Profiling**: Get execution time and memory usage for each line of a function.
32
+ - **Shared Logging**: Log profiler outputs to a `.txt` file.
33
+ - **File Exports**: Export profiling data in various formats.
34
+ - **New Options**:
35
+ - `enabled`: A boolean to enable or disable profiling.
36
+ - `log_level`: Set the logging level to "info" or "debug".
37
+
38
+ ## Export Formats
39
+
40
+ | Format | `function_profile` | `line_by_line_profile` |
41
+ |--------|--------------------|------------------------|
42
+ | `txt` | ✅ | ❌ |
43
+ | `json` | ✅ | ✅ |
44
+ | `csv` | ✅ | ✅ |
45
+ | `html` | ✅ | ✅ |
46
+ | `xml` | ✅ | ✅ |
47
+ | `md` | ✅ | ✅ |
48
+ | `yaml` | ✅ | ✅ |
49
+ | `toml` | ✅ | ✅ |
50
+
51
+ ## Usage
52
+
53
+ ### Function Profiling
54
+
55
+ ```python
56
+ from funcprofiler import function_profile
57
+
58
+ @function_profile(export_format="html", shared_log=True, log_level="debug")
59
+ def some_function():
60
+ return "Hello World."
61
+
62
+ message = some_function()
63
+ ```
64
+
65
+ ### Line-by-Line Profiling
66
+
67
+ ```python
68
+ from funcprofiler import line_by_line_profile
69
+
70
+ @line_by_line_profile(shared_log=True, enabled=True)
71
+ def some_complicated_function(n):
72
+ total = 0
73
+ for i in range(n):
74
+ for j in range(i):
75
+ total += (i * j) ** 0.5
76
+ return total
77
+
78
+ total = some_complicated_function(1000)
79
+ ```
80
+
81
+ ## Contributing
82
+
83
+ Contributions are welcome! Please open an issue or submit a pull request on [GitHub](https://github.com/infinitode/funcprofiler).
84
+
85
+ ## License
86
+
87
+ FuncProfiler is released under the **MIT License (Modified)**. See the [LICENSE](https://github.com/infinitode/funcprofiler/blob/main/LICENSE) file for details.
@@ -11,14 +11,15 @@ import xml.etree.ElementTree as ET
11
11
 
12
12
  __all__ = ['function_profile', 'line_by_line_profile', 'export_function_profile_data', 'export_profiling_data']
13
13
 
14
- def function_profile(export_format: Optional[str] = None, filename: Optional[str] = None, shared_log: bool = False) -> Callable:
14
+ def function_profile(export_format: Optional[str] = None, filename: Optional[str] = None, shared_log: bool = False, enabled: bool = True, log_level: str = "info") -> Callable:
15
15
  """Decorator factory to profile the execution time and memory usage of a function.
16
16
 
17
17
  Parameters:
18
18
  export_format (Optional[str]): The format to export the profiling data ('txt', 'json', 'csv', 'html').
19
19
  filename (Optional[str]): The name of the output file (without extension).
20
20
  shared_log (Optional[bool]): If True, log to a shared file for all profiled functions.
21
-
21
+ enabled (bool): If False, the decorator will not perform any profiling.
22
+ log_level (str): The logging level ("info" or "debug").
22
23
  Returns:
23
24
  Callable: The profiling wrapper or decorator function.
24
25
  """
@@ -27,6 +28,9 @@ def function_profile(export_format: Optional[str] = None, filename: Optional[str
27
28
  def decorator(func: Callable) -> Callable:
28
29
  @functools.wraps(func)
29
30
  def wrapper(*args, **kwargs):
31
+ if not enabled:
32
+ return func(*args, **kwargs)
33
+
30
34
  # Start time and memory tracking
31
35
  tracemalloc.start()
32
36
  start_time = time.time()
@@ -49,8 +53,16 @@ def function_profile(export_format: Optional[str] = None, filename: Optional[str
49
53
 
50
54
  # Prepare data for exporting
51
55
  profiling_data = {
56
+ "function_name": func.__name__,
52
57
  "execution_times": end_time - start_time,
53
58
  "memory_usage": current / 10**6, # Convert to MB
59
+ "peak_memory_usage": peak / 10**6,
60
+ "timestamp": time.strftime('%Y-%m-%d %H:%M:%S'),
61
+ "arguments": str({'args': args, 'kwargs': kwargs}),
62
+ "return_value": str(result),
63
+ "filepath": inspect.getfile(func),
64
+ "line_number": inspect.getsourcelines(func)[1],
65
+ "docstring": func.__doc__
54
66
  }
55
67
 
56
68
  if export_format:
@@ -58,8 +70,14 @@ def function_profile(export_format: Optional[str] = None, filename: Optional[str
58
70
  export_function_profile_data(profiling_data, func, export_format, file)
59
71
 
60
72
  # Display the profiling results
61
- print(f"[FUNCPROFILER] Function '{func.__name__}' executed in {end_time - start_time:.12f}s")
62
- print(f"[FUNCPROFILER] Current memory usage: {current / 10**6:.12f}MB; Peak: {peak / 10**6:.12f}MB")
73
+ if log_level == "info":
74
+ print(f"[FUNCPROFILER] Function '{func.__name__}' executed in {end_time - start_time:.12f}s")
75
+ print(f"[FUNCPROFILER] Current memory usage: {current / 10**6:.12f}MB; Peak: {peak / 10**6:.12f}MB")
76
+ elif log_level == "debug":
77
+ print(f"[FUNCPROFILER-DEBUG] Function '{func.__name__}' called with args: {args}, kwargs: {kwargs}")
78
+ print(f"[FUNCPROFILER-DEBUG] Execution Time: {end_time - start_time:.12f}s")
79
+ print(f"[FUNCPROFILER-DEBUG] Memory Usage: {current / 10**6:.6f}MB; Peak: {peak / 10**6:.6f}MB")
80
+ print(f"[FUNCPROFILER-DEBUG] Return Value: {result}")
63
81
 
64
82
  # Log the profiling data
65
83
  if shared_log and log_file:
@@ -85,58 +103,100 @@ def export_function_profile_data(profiling_data: dict, func: Callable, export_fo
85
103
  export_format (str): The format for export ('txt', 'json', 'csv', 'html', 'xml', 'md').
86
104
  filename (str): The output filename without extension.
87
105
  """
88
- execution_time = profiling_data["execution_times"]
89
- memory_usage = profiling_data["memory_usage"]
90
-
91
106
  if export_format == "txt":
92
107
  with open(f"{filename}.txt", 'w') as f:
93
- f.write(f"Function: {func.__name__}\n")
94
- f.write(f"Execution Time: {execution_time:.12f}s\n")
95
- f.write(f"Memory Usage: {memory_usage:.6f}MB\n")
108
+ for key, value in profiling_data.items():
109
+ f.write(f"{key.replace('_', ' ').title()}: {value}\n")
96
110
 
97
111
  elif export_format == "json":
112
+ output_data = {
113
+ "metadata": {
114
+ "profile_type": "function_profile",
115
+ "export_time": time.strftime('%Y-%m-%d %H:%M:%S')
116
+ },
117
+ "profile": profiling_data
118
+ }
98
119
  with open(f"{filename}.json", 'w') as f:
99
- json.dump({
100
- "function": func.__name__,
101
- "execution_time": execution_time,
102
- "memory_usage": memory_usage
103
- }, f, indent=4)
120
+ json.dump(output_data, f, indent=4)
104
121
 
105
122
  elif export_format == "csv":
106
123
  with open(f"{filename}.csv", 'w', newline='') as f:
107
124
  writer = csv.writer(f)
108
- writer.writerow(["Function", "Execution Time (s)", "Memory Usage (MB)"])
109
- writer.writerow([func.__name__, execution_time, memory_usage])
125
+ writer.writerow(profiling_data.keys())
126
+ writer.writerow(profiling_data.values())
110
127
 
111
128
  elif export_format == "html":
112
129
  with open(f"{filename}.html", 'w') as f:
113
- f.write("<html><head><title>Function Profiling Report</title></head><body>")
114
- f.write(f"<h1>Function: {func.__name__}</h1>")
115
- f.write(f"<p>Execution Time: <strong>{execution_time:.12f}s</strong></p>")
116
- f.write(f"<p>Memory Usage: <strong>{memory_usage:.6f}MB</strong></p>")
130
+ f.write("<html><head><title>Function Profiling Report</title>")
131
+ f.write("""
132
+ <style>
133
+ body { font-family: Arial, sans-serif; }
134
+ table { border-collapse: collapse; width: 60%; margin: 20px 0; }
135
+ th, td { border: 1px solid #dddddd; text-align: left; padding: 8px; }
136
+ th { background-color: #f2f2f2; }
137
+ </style>
138
+ """)
139
+ f.write("</head><body>")
140
+ f.write(f"<h1>Function Profiling Report: {profiling_data['function_name']}</h1>")
141
+ f.write("<table>")
142
+ f.write("<tr><th>Metric</th><th>Value</th></tr>")
143
+ for key, value in profiling_data.items():
144
+ f.write(f"<tr><td>{key.replace('_', ' ').title()}</td><td>{value}</td></tr>")
145
+ f.write("</table>")
117
146
  f.write("</body></html>")
118
147
 
119
148
  elif export_format == "xml":
120
149
  root = ET.Element("FunctionProfile")
121
- ET.SubElement(root, "Function").text = func.__name__
122
- ET.SubElement(root, "ExecutionTime").text = f"{execution_time:.12f}"
123
- ET.SubElement(root, "MemoryUsage").text = f"{memory_usage:.6f}"
150
+ for key, value in profiling_data.items():
151
+ ET.SubElement(root, key.replace('_', ' ').title().replace(' ', '')).text = str(value)
124
152
  tree = ET.ElementTree(root)
125
153
  tree.write(f"{filename}.xml")
126
154
 
127
155
  elif export_format == "md":
128
156
  with open(f"{filename}.md", 'w') as f:
129
- f.write(f"# Function Profiling Report for {func.__name__}\n\n")
130
- f.write(f"**Execution Time:** {execution_time:.12f}s\n\n")
131
- f.write(f"**Memory Usage:** {memory_usage:.6f}MB\n")
157
+ f.write(f"# Function Profiling Report for {profiling_data['function_name']}\n\n")
158
+ f.write("| Metric | Value |\n")
159
+ f.write("|--------|-------|\n")
160
+ for key, value in profiling_data.items():
161
+ f.write(f"| {key.replace('_', ' ').title()} | {value} |\n")
162
+
163
+ elif export_format == "yaml":
164
+ def to_yaml_string(data):
165
+ lines = []
166
+ for key, value in data.items():
167
+ if isinstance(value, str) and '\n' in value:
168
+ lines.append(f"{key}: |")
169
+ for line in value.splitlines():
170
+ lines.append(f" {line}")
171
+ else:
172
+ lines.append(f"{key}: {json.dumps(value, ensure_ascii=False)}")
173
+ return "\n".join(lines)
174
+
175
+ with open(f"{filename}.yaml", 'w') as f:
176
+ f.write(to_yaml_string(profiling_data))
177
+
178
+ elif export_format == "toml":
179
+ def to_toml_string(data):
180
+ lines = []
181
+ for key, value in data.items():
182
+ if isinstance(value, str) and '\n' in value:
183
+ lines.append(f"{key} = '''\n{value}'''")
184
+ else:
185
+ lines.append(f"{key} = {json.dumps(value, ensure_ascii=False)}")
186
+ return "\n".join(lines)
187
+
188
+ with open(f"{filename}.toml", 'w') as f:
189
+ f.write(to_toml_string(profiling_data))
132
190
 
133
191
  else:
134
- raise ValueError("Unsupported export format. Use 'txt', 'json', 'csv', 'html', 'xml', or 'md'.")
192
+ raise ValueError("Unsupported export format. Use 'txt', 'json', 'csv', 'html', 'xml', 'md', 'yaml', or 'toml'.")
135
193
 
136
194
  def line_by_line_profile(
137
195
  export_format: Optional[str] = None,
138
196
  filename: Optional[str] = None,
139
- shared_log: bool = False
197
+ shared_log: bool = False,
198
+ enabled: bool = True,
199
+ log_level: str = "info"
140
200
  ) -> Callable:
141
201
  """Decorator for line-by-line profiling of a function with optional data export and shared logging.
142
202
 
@@ -144,7 +204,8 @@ def line_by_line_profile(
144
204
  export_format (Optional[str]): The format to export the profiling data ('json', 'csv', 'html').
145
205
  filename (Optional[str]): The name of the output file (without extension).
146
206
  shared_log (Optional[bool]): If True, log to a shared file for all profiled functions.
147
-
207
+ enabled (bool): If False, the decorator will not perform any profiling.
208
+ log_level (str): The logging level ("info" or "debug").
148
209
  Returns:
149
210
  Callable: The profiling wrapper or decorator function.
150
211
  """
@@ -153,6 +214,9 @@ def line_by_line_profile(
153
214
  def decorator(func: Callable) -> Callable:
154
215
  @functools.wraps(func)
155
216
  def wrapper(*args, **kwargs):
217
+ if not enabled:
218
+ return func(*args, **kwargs)
219
+
156
220
  line_execution_times: Dict[int, float] = {}
157
221
  line_memory_usage: Dict[int, float] = {}
158
222
  current_line_start_time: Optional[float] = None
@@ -196,22 +260,40 @@ def line_by_line_profile(
196
260
  tracemalloc.stop()
197
261
 
198
262
  # Print profiling data
199
- print(f"\nLine-by-Line Profiling for '{func.__name__}':")
200
- source_lines, starting_line = inspect.getsourcelines(func)
201
- for line_no in sorted(line_execution_times.keys()):
202
- actual_line = line_no - starting_line + 1
203
- source_line = source_lines[actual_line - 1].strip()
204
- exec_time = line_execution_times[line_no]
205
- mem_usage = line_memory_usage.get(line_no, 0)
206
- print(f"Line {line_no} ({source_line}): "
207
- f"Execution Time: {exec_time:.12f}s, "
208
- f"Memory Usage: {mem_usage:.12f}MB")
209
-
210
- # Collect the profiling data for the report
211
- profiling_data = {
212
- "line_execution_times": line_execution_times,
213
- "line_memory_usage": line_memory_usage
214
- }
263
+ if log_level == "info":
264
+ print(f"\nLine-by-Line Profiling for '{func.__name__}':")
265
+ source_lines, starting_line = inspect.getsourcelines(func)
266
+ for line_no in sorted(line_execution_times.keys()):
267
+ actual_line = line_no - starting_line + 1
268
+ source_line = source_lines[actual_line - 1].strip()
269
+ exec_time = line_execution_times[line_no]
270
+ mem_usage = line_memory_usage.get(line_no, 0)
271
+ print(f"Line {line_no} ({source_line}): "
272
+ f"Execution Time: {exec_time:.12f}s, "
273
+ f"Memory Usage: {mem_usage:.12f}MB")
274
+ elif log_level == "debug":
275
+ print(f"\n[DEBUG] Line-by-Line Profiling for '{func.__name__}':")
276
+ source_lines, starting_line = inspect.getsourcelines(func)
277
+ for line_no in sorted(line_execution_times.keys()):
278
+ actual_line = line_no - starting_line + 1
279
+ source_line = source_lines[actual_line - 1].strip()
280
+ exec_time = line_execution_times[line_no]
281
+ mem_usage = line_memory_usage.get(line_no, 0)
282
+ print(f"[DEBUG] Line {line_no} ({source_line}): "
283
+ f"Execution Time: {exec_time:.12f}s, "
284
+ f"Memory Usage: {mem_usage:.12f}MB")
285
+
286
+ # Collect the profiling data for the report
287
+ profiling_data = {
288
+ "function_name": func.__name__,
289
+ "timestamp": time.strftime('%Y-%m-%d %H:%M:%S'),
290
+ "arguments": str({'args': args, 'kwargs': kwargs}),
291
+ "return_value": str(result),
292
+ "filepath": inspect.getfile(func),
293
+ "docstring": func.__doc__,
294
+ "line_execution_times": line_execution_times,
295
+ "line_memory_usage": line_memory_usage
296
+ }
215
297
 
216
298
  if export_format:
217
299
  file = filename or f"{func.__name__}_lblprofile_report"
@@ -277,98 +359,123 @@ def export_profiling_data(
277
359
 
278
360
  # Handle different export formats
279
361
  if export_format == 'json':
280
- output_path = f"{filename}.json"
281
- # Check if the file exists to append or create
282
- if os.path.exists(output_path):
283
- with open(output_path, 'r') as json_file:
284
- existing_data = json.load(json_file)
285
- existing_data.extend(export_data)
286
- else:
287
- existing_data = export_data
288
-
289
- with open(output_path, 'w') as json_file:
290
- json.dump(existing_data, json_file, indent=4)
291
- print(f"[PROFILER] JSON report generated at: {output_path}")
362
+ output_data = {
363
+ "metadata": {
364
+ "profile_type": "line_by_line_profile",
365
+ "export_time": time.strftime('%Y-%m-%d %H:%M:%S'),
366
+ "function_name": func.__name__,
367
+ "filepath": inspect.getfile(func),
368
+ "docstring": func.__doc__
369
+ },
370
+ "profile": export_data
371
+ }
372
+ with open(f"{filename}.json", 'w') as json_file:
373
+ json.dump(output_data, json_file, indent=4)
374
+ print(f"[PROFILER] JSON report generated at: {filename}.json")
292
375
 
293
376
  elif export_format == 'csv':
294
377
  output_path = f"{filename}.csv"
295
- # Check if the file exists to determine write mode
296
378
  file_mode = 'a' if os.path.exists(output_path) else 'w'
297
-
298
379
  with open(output_path, mode=file_mode, newline='') as csvfile:
299
- writer = csv.DictWriter(csvfile, fieldnames=['Function Name', 'Line Number', 'Source Code', 'Execution Time (s)', 'Memory Usage (MB)'])
380
+ writer = csv.DictWriter(csvfile, fieldnames=export_data[0].keys())
300
381
  if file_mode == 'w':
301
- writer.writeheader() # Write header only for new file
302
- for data in export_data:
303
- writer.writerow(data)
382
+ writer.writeheader()
383
+ writer.writerows(export_data)
304
384
  print(f"[PROFILER] CSV report generated at: {output_path}")
305
385
 
306
386
  elif export_format == 'html':
307
387
  output_path = f"{filename}.html"
308
388
  file_mode = 'a' if os.path.exists(output_path) else 'w'
309
-
310
389
  if file_mode == 'w':
311
- html_content = """
390
+ html_content = f"""
312
391
  <html>
313
- <head><title>Line-by-Line Profiling Report</title></head>
392
+ <head>
393
+ <title>Line-by-Line Profiling Report</title>
394
+ <style>
395
+ body {{ font-family: Arial, sans-serif; }}
396
+ table {{ border-collapse: collapse; width: 100%; }}
397
+ th, td {{ border: 1px solid #dddddd; text-align: left; padding: 8px; }}
398
+ th {{ background-color: #f2f2f2; }}
399
+ </style>
400
+ </head>
314
401
  <body>
315
- <h2>Line-by-Line Profiling Report</h2>
316
- <table border="1">
317
- <tr>
318
- <th>Function Name</th>
319
- <th>Line Number</th>
320
- <th>Source Code</th>
321
- <th>Execution Time (s)</th>
322
- <th>Memory Usage (MB)</th>
323
- </tr>
402
+ <h2>Line-by-Line Profiling Report for {func.__name__}</h2>
403
+ <table>
404
+ <tr>
405
+ <th>Line Number</th>
406
+ <th>Source Code</th>
407
+ <th>Execution Time (s)</th>
408
+ <th>Memory Usage (MB)</th>
409
+ </tr>
324
410
  """
325
411
  else:
326
- html_content = ""
412
+ with open(output_path, 'r') as f:
413
+ html_content = f.read().replace("</table></body></html>", "")
327
414
 
328
415
  for data in export_data:
329
416
  html_content += f"""
330
417
  <tr>
331
- <td>{data['Function Name']}</td>
332
418
  <td>{data['Line Number']}</td>
333
419
  <td>{data['Source Code']}</td>
334
420
  <td>{data['Execution Time (s)']}</td>
335
421
  <td>{data['Memory Usage (MB)']}</td>
336
422
  </tr>
337
423
  """
338
-
339
- if file_mode == 'w':
340
- html_content += """
341
- </table>
342
- </body>
343
- </html>
344
- """
345
-
346
- with open(output_path, mode='a') as f:
424
+ html_content += "</table></body></html>"
425
+ with open(output_path, 'w') as f:
347
426
  f.write(html_content)
348
427
  print(f"[PROFILER] HTML report generated at: {output_path}")
349
428
 
350
429
  elif export_format == 'xml':
351
- root = ET.Element("FunctionProfile")
430
+ root = ET.Element("LineByLineProfile")
352
431
  for data in export_data:
353
432
  line_element = ET.SubElement(root, "Line")
354
- ET.SubElement(line_element, "FunctionName").text = data['Function Name']
355
- ET.SubElement(line_element, "LineNumber").text = data['Line Number']
356
- ET.SubElement(line_element, "SourceCode").text = data['Source Code']
357
- ET.SubElement(line_element, "ExecutionTime").text = data['Execution Time (s)']
358
- ET.SubElement(line_element, "MemoryUsage").text = data['Memory Usage (MB)']
433
+ for key, value in data.items():
434
+ ET.SubElement(line_element, key.replace(' ', '')).text = str(value)
359
435
  tree = ET.ElementTree(root)
360
436
  tree.write(f"{filename}.xml")
361
437
  print(f"[PROFILER] XML report generated at: {filename}.xml")
362
438
 
363
439
  elif export_format == 'md':
364
- output_path = f"{filename}.md"
365
- with open(output_path, 'w') as f:
440
+ with open(f"{filename}.md", 'w') as f:
366
441
  f.write(f"# Line-by-Line Profiling Report for {func.__name__}\n\n")
367
442
  f.write("| Line Number | Source Code | Execution Time (s) | Memory Usage (MB) |\n")
368
443
  f.write("|-------------|-------------|--------------------|-------------------|\n")
369
444
  for data in export_data:
370
- f.write(f"| {data['Line Number']} | {data['Source Code']} | {data['Execution Time (s)']} | {data['Memory Usage (MB)']} |\n")
371
- print(f"[PROFILER] Markdown report generated at: {output_path}")
445
+ f.write(f"| {data['Line Number']} | `{data['Source Code']}` | {data['Execution Time (s)']} | {data['Memory Usage (MB)']} |\n")
446
+ print(f"[PROFILER] Markdown report generated at: {filename}.md")
447
+
448
+ elif export_format == 'yaml':
449
+ def to_yaml_string(data):
450
+ lines = []
451
+ for item in data:
452
+ lines.append("-")
453
+ for key, value in item.items():
454
+ if isinstance(value, str) and '\n' in value:
455
+ lines.append(f" {key}: |")
456
+ for line in value.splitlines():
457
+ lines.append(f" {line}")
458
+ else:
459
+ lines.append(f" {key}: {json.dumps(value, ensure_ascii=False)}")
460
+ return "\n".join(lines)
461
+
462
+ with open(f"{filename}.yaml", 'w') as f:
463
+ f.write(to_yaml_string(export_data))
464
+
465
+ elif export_format == 'toml':
466
+ def to_toml_string(data):
467
+ lines = []
468
+ for item in data:
469
+ lines.append("[[profile]]")
470
+ for key, value in item.items():
471
+ if isinstance(value, str) and '\n' in value:
472
+ lines.append(f"{key} = '''\n{value}'''")
473
+ else:
474
+ lines.append(f"{key} = {json.dumps(value, ensure_ascii=False)}")
475
+ return "\n".join(lines)
476
+
477
+ with open(f"{filename}.toml", 'w') as f:
478
+ f.write(to_toml_string(export_data))
372
479
 
373
480
  else:
374
481
  print(f"[PROFILER] Unsupported export format: {export_format}")
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: funcprofiler
3
- Version: 1.0.2
3
+ Version: 1.1.0
4
4
  Summary: An open-source Python library for finding bottlenecks in code. Includes function profiling, data exports, logging, and even line-by-line profiling, for more control.
5
5
  Home-page: https://github.com/infinitode/funcprofiler
6
6
  Author: Infinitode Pty Ltd
@@ -25,6 +25,7 @@ Dynamic: classifier
25
25
  Dynamic: description
26
26
  Dynamic: description-content-type
27
27
  Dynamic: home-page
28
+ Dynamic: license-file
28
29
  Dynamic: requires-python
29
30
  Dynamic: summary
30
31
 
@@ -37,8 +38,11 @@ Dynamic: summary
37
38
 
38
39
  An open-source Python library for identifying bottlenecks in code. It includes function profiling, data exports, logging, and line-by-line profiling for more granular control.
39
40
 
40
- ## Changelog (v.1.0.2):
41
- - Added support for 2 new export formats: `xml` and `md` in both function profiling, and line-by-line profiling.
41
+ ## Changelog (v.1.1.0):
42
+ - Added support for 2 new export formats: `yaml` and `toml`.
43
+ - Exports now include more information: peak memory usage, timestamp, arguments, return value, filepath, line number, and docstring.
44
+ - Added `enabled` and `log_level` options to the decorators.
45
+ - Improved export formats for better readability.
42
46
 
43
47
  ## Installation
44
48
 
@@ -50,25 +54,30 @@ pip install funcprofiler
50
54
 
51
55
  ## Supported Python Versions
52
56
 
53
- FuncProfiler supports the following Python versions:
54
-
55
- - Python 3.6
56
- - Python 3.7
57
- - Python 3.8
58
- - Python 3.9
59
- - Python 3.10
60
- - Python 3.11 and later (preferred)
61
-
62
- Please ensure that you have one of these Python versions installed. FuncProfiler may not function as expected on earlier versions.
57
+ FuncProfiler supports Python 3.6 and later.
63
58
 
64
59
  ## Features
65
60
 
66
- - **Function Profiling**: Monitor a function's memory usage and execution time to identify performance issues.
67
- - **Line-by-Line Profiling**: Return execution time and memory usage for each line of any given function.
68
- - **Shared Logging**: Log outputs of functions triggered by the line-by-line and function profilers, storing results in a `.txt` file.
69
- - **File Exports**: Export profiling data from functions in `csv`, `json`, `html`, `xml` and `md` formats, for both line-by-line profiling and function profiling.
70
- > [!NOTE]
71
- > View more export types in the [official documentation](https://infinitode-docs.gitbook.io/documentation/package-documentation/funcprofiler-package-documentation).
61
+ - **Function Profiling**: Monitor a function's memory usage and execution time.
62
+ - **Line-by-Line Profiling**: Get execution time and memory usage for each line of a function.
63
+ - **Shared Logging**: Log profiler outputs to a `.txt` file.
64
+ - **File Exports**: Export profiling data in various formats.
65
+ - **New Options**:
66
+ - `enabled`: A boolean to enable or disable profiling.
67
+ - `log_level`: Set the logging level to "info" or "debug".
68
+
69
+ ## Export Formats
70
+
71
+ | Format | `function_profile` | `line_by_line_profile` |
72
+ |--------|--------------------|------------------------|
73
+ | `txt` | ✅ | ❌ |
74
+ | `json` | ✅ | ✅ |
75
+ | `csv` | ✅ | ✅ |
76
+ | `html` | ✅ | ✅ |
77
+ | `xml` | ✅ | ✅ |
78
+ | `md` | ✅ | ✅ |
79
+ | `yaml` | ✅ | ✅ |
80
+ | `toml` | ✅ | ✅ |
72
81
 
73
82
  ## Usage
74
83
 
@@ -77,12 +86,10 @@ Please ensure that you have one of these Python versions installed. FuncProfiler
77
86
  ```python
78
87
  from funcprofiler import function_profile
79
88
 
80
- # Exporting as `html` with logging enabled
81
- @function_profile(export_format="html", shared_log=True)
89
+ @function_profile(export_format="html", shared_log=True, log_level="debug")
82
90
  def some_function():
83
91
  return "Hello World."
84
92
 
85
- # Call the function
86
93
  message = some_function()
87
94
  ```
88
95
 
@@ -91,28 +98,21 @@ message = some_function()
91
98
  ```python
92
99
  from funcprofiler import line_by_line_profile
93
100
 
94
- # Logging enabled without exports
95
- @line_by_line_profile(shared_log=True)
101
+ @line_by_line_profile(shared_log=True, enabled=True)
96
102
  def some_complicated_function(n):
97
103
  total = 0
98
104
  for i in range(n):
99
105
  for j in range(i):
100
- total += (i * j) ** 0.5 # Square root calculation
106
+ total += (i * j) ** 0.5
101
107
  return total
102
108
 
103
- # Call the function
104
109
  total = some_complicated_function(1000)
105
110
  ```
106
111
 
107
- > [!NOTE]
108
- > FuncProfiler can be added to any function using the callable format: `@funcprofiler_function_name(expected_arguments)`.
109
-
110
112
  ## Contributing
111
113
 
112
- Contributions are welcome! If you encounter issues, have suggestions, or wish to contribute to FuncProfiler, please open an issue or submit a pull request on [GitHub](https://github.com/infinitode/funcprofiler).
114
+ Contributions are welcome! Please open an issue or submit a pull request on [GitHub](https://github.com/infinitode/funcprofiler).
113
115
 
114
116
  ## License
115
117
 
116
- FuncProfiler is released under the terms of the **MIT License (Modified)**. Please see the [LICENSE](https://github.com/infinitode/funcprofiler/blob/main/LICENSE) file for the full text.
117
-
118
- **Modified License Clause**: The modified license clause allows users to create derivative works based on the FuncProfiler software. However, it requires that any substantial changes to the software be clearly distinguished from the original work and distributed under a different name.
118
+ FuncProfiler is released under the **MIT License (Modified)**. See the [LICENSE](https://github.com/infinitode/funcprofiler/blob/main/LICENSE) file for details.
@@ -5,7 +5,7 @@ with open("README.md", "r", encoding="utf-8") as fh:
5
5
 
6
6
  setup(
7
7
  name='funcprofiler',
8
- version='1.0.2',
8
+ version='1.1.0',
9
9
  author='Infinitode Pty Ltd',
10
10
  author_email='infinitode.ltd@gmail.com',
11
11
  description='An open-source Python library for finding bottlenecks in code. Includes function profiling, data exports, logging, and even line-by-line profiling, for more control.',
@@ -1,88 +0,0 @@
1
- # FuncProfiler
2
- ![Python Version](https://img.shields.io/badge/python-3.13-blue.svg)
3
- [![Code Size](https://img.shields.io/github/languages/code-size/infinitode/funcprofiler)](https://github.com/infinitode/funcprofiler)
4
- ![Downloads](https://pepy.tech/badge/funcprofiler)
5
- ![License Compliance](https://img.shields.io/badge/license-compliance-brightgreen.svg)
6
- ![PyPI Version](https://img.shields.io/pypi/v/funcprofiler)
7
-
8
- An open-source Python library for identifying bottlenecks in code. It includes function profiling, data exports, logging, and line-by-line profiling for more granular control.
9
-
10
- ## Changelog (v.1.0.2):
11
- - Added support for 2 new export formats: `xml` and `md` in both function profiling, and line-by-line profiling.
12
-
13
- ## Installation
14
-
15
- You can install FuncProfiler using pip:
16
-
17
- ```bash
18
- pip install funcprofiler
19
- ```
20
-
21
- ## Supported Python Versions
22
-
23
- FuncProfiler supports the following Python versions:
24
-
25
- - Python 3.6
26
- - Python 3.7
27
- - Python 3.8
28
- - Python 3.9
29
- - Python 3.10
30
- - Python 3.11 and later (preferred)
31
-
32
- Please ensure that you have one of these Python versions installed. FuncProfiler may not function as expected on earlier versions.
33
-
34
- ## Features
35
-
36
- - **Function Profiling**: Monitor a function's memory usage and execution time to identify performance issues.
37
- - **Line-by-Line Profiling**: Return execution time and memory usage for each line of any given function.
38
- - **Shared Logging**: Log outputs of functions triggered by the line-by-line and function profilers, storing results in a `.txt` file.
39
- - **File Exports**: Export profiling data from functions in `csv`, `json`, `html`, `xml` and `md` formats, for both line-by-line profiling and function profiling.
40
- > [!NOTE]
41
- > View more export types in the [official documentation](https://infinitode-docs.gitbook.io/documentation/package-documentation/funcprofiler-package-documentation).
42
-
43
- ## Usage
44
-
45
- ### Function Profiling
46
-
47
- ```python
48
- from funcprofiler import function_profile
49
-
50
- # Exporting as `html` with logging enabled
51
- @function_profile(export_format="html", shared_log=True)
52
- def some_function():
53
- return "Hello World."
54
-
55
- # Call the function
56
- message = some_function()
57
- ```
58
-
59
- ### Line-by-Line Profiling
60
-
61
- ```python
62
- from funcprofiler import line_by_line_profile
63
-
64
- # Logging enabled without exports
65
- @line_by_line_profile(shared_log=True)
66
- def some_complicated_function(n):
67
- total = 0
68
- for i in range(n):
69
- for j in range(i):
70
- total += (i * j) ** 0.5 # Square root calculation
71
- return total
72
-
73
- # Call the function
74
- total = some_complicated_function(1000)
75
- ```
76
-
77
- > [!NOTE]
78
- > FuncProfiler can be added to any function using the callable format: `@funcprofiler_function_name(expected_arguments)`.
79
-
80
- ## Contributing
81
-
82
- Contributions are welcome! If you encounter issues, have suggestions, or wish to contribute to FuncProfiler, please open an issue or submit a pull request on [GitHub](https://github.com/infinitode/funcprofiler).
83
-
84
- ## License
85
-
86
- FuncProfiler is released under the terms of the **MIT License (Modified)**. Please see the [LICENSE](https://github.com/infinitode/funcprofiler/blob/main/LICENSE) file for the full text.
87
-
88
- **Modified License Clause**: The modified license clause allows users to create derivative works based on the FuncProfiler software. However, it requires that any substantial changes to the software be clearly distinguished from the original work and distributed under a different name.
File without changes
File without changes