Name | perftracker JSON |
Version |
1.4.0
JSON |
| download |
home_page | https://github.com/vertyco/perftracker |
Summary | PerfTracker is a lightweight function performance monitoring framework |
upload_time | 2024-01-06 20:01:12 |
maintainer | |
docs_url | None |
author | vertyco |
requires_python | >=3.9 |
license | |
keywords |
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# PerfTracker
PerfTracker is a erformance tracking package designed to assist developers in monitoring and tracking the execution time of their functions. It provides a straightforward and efficient way to measure function performance, enabling you to optimize your code effectively.
[![badge](https://img.shields.io/pypi/v/perftracker)](https://pypi.org/project/perftracker/)
[![badge](https://img.shields.io/pypi/dm/perftracker)](https://pypi.org/project/perftracker/)
## Features
- **Ease of Use**: Simply add a decorator to your functions.
- **Flexibility**: Can be used without decorator for manual tracking.
- **Detailed Statistics**: PerfTracker provides comprehensive statistics about your function's performance. It allows you to get the execution times and calculate the average calls per minute over a certain period. This information can be crucial in identifying bottlenecks in your code and optimizing it.
- **No Dependencies**: PerfTracker does not require any 3rd party packages to function.
- **Debug Logging**: Logs function execution deltas in real time.
```
[09:48:58] DEBUG [perftracker] levelup.levelup.message_handler took 0.0017ms to complete.
[09:49:18] DEBUG [perftracker] levelup.levelup.save_cache took 0.001099ms to complete.
```
## Disclaimer
This package uses a global variable `_perf` for the performance model. It uses a key schema
of `module_name.function_name` to avoid interference when multiple packages use it for tracking.
## Installation
To install PerfTracker using pip, Run the following command in your terminal:
```bash
pip install perftracker
```
### Methods
PerfTracker provides several methods to track and retrieve function performance data:
- `@perf(max_entries=None)`: A decorator to measure and record the execution time of a function. If `max_entries` is set, it will limit the number of records kept for the function to this value.
- `get_stats()`: Returns the current Performance instance, which contains all recorded performance data.
- `Performance.add(function, exe_time, max_entries=None)`: Adds an execution time record for a function. You can use this method to manually add execution time records.
- `Performance.get(function)`: Returns the execution time records for a function. This can be useful if you want to analyze the performance data further.
- `Performance.cpm(function, time_delta)`: Calculates the average calls per minute (CPM) of a function over a certain period. This can give you an idea of how frequently a function is called.
- `Performance.avg_time(function, time_delta)`: Calculate the average time a function takes to execute over a certain period. This can help you identify slow functions that may need optimization.
## Usage
Using PerfTracker is straightforward. Here are some examples:
### Basic Usage
```python
from perftracker import perf, get_stats
@perf(max_entries=100)
def my_function():
# Your code here...
# Get performance statistics
stats = get_stats()
```
### Retrieving Execution Time Records
```python
from perftracker import perf, get_stats
@perf(max_entries=100)
def my_function():
# Your code here...
# Get performance statistics
stats = get_stats()
# Retrieve execution time records
records = stats.get(my_function)
```
### Calculating Calls Per Minute
```python
from perftracker import perf, get_stats
from datetime import timedelta
@perf(max_entries=100)
def my_function():
# Your code here...
# Get performance statistics
stats = get_stats()
# Calculate calls per minute for the last hour
cpm = stats.cpm(my_function, timedelta(hours=1))
```
### Tracking Things Manually
```python
from perftracker import get_stats
from time import perf_counter
def some_function():
stats = get_stats()
start_time = perf_counter()
... # Some code that takes time...
end_time = perf_counter()
delta = (end_time - start_time) * 1000 # Use milliseconds
# Add time manually, the 'add' method can take strings too
stats.add("my_custom_function_key", delta)
```
### Full Usage
```python
from perftracker import perf, get_stats
from datetime import timedelta
from time import sleep
import random
@perf(max_entries=100)
def my_function():
# Your code here...
# Run the code a few times
for _ in range(10):
my_function()
sleep(random.random())
# Get performance statistics
stats = get_stats()
# Get a list of Record objects (Record represents when a function was called)
records = stats.get(my_function)
# Get first time the function was called
record = records[0]
# (float) Time this particular entry took to execute in ms
execution_time = record.exe_time
# (datetime.datetime) in UTC timezone naive, the time when this entry was created
timestamp = record.timestamp
# Calls per minute (float)
cpm = stats.cpm(my_function)
# Average execution time (float)
avg_exe_time = stats.avg_time(my_function)
```
### Discord Bot Cog Usage
PerfTracker can also be used in a Discord bot environment to help you track down bottlenecks in your bot's performance. Here is an example of how you can use PerfTracker in a Discord bot cog:
```python
from discord.ext import commands
from perftracker import perf, get_stats
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@perf(max_entries=100)
async def slow_function(self, ctx):
# Your sussy code here...
@commands.command()
async def performance(self, ctx):
stats = get_stats()
records = stats.get(self.slow_function)
if records:
avg_time = stats.avg_time(self.slow_function)
await ctx.send(f"Average execution time for slow_function: {avg_time}ms")
else:
await ctx.send(f"No performance records found for {function_name}")
def setup(bot):
bot.add_cog(MyCog(bot))
```
In this example, `slow_function` is a function in a Discord bot cog that is tracked by PerfTracker. The `performance` command can be used to retrieve the average execution time of the specific command.
You can replace `slow_function` with any function in your bot that you want to track. The performance statistics are stored in memory and will be lost when the bot is restarted.
Please note that this example assumes you have basic knowledge of how to create and use cogs in a Discord bot. If you are unfamiliar with this, you can read the [Discord.py Cogs guide](https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html).
## Performance Comparison
PerfTracker is designed to have minimal overhead, allowing you to monitor your program's performance without significantly affecting its execution time. The following graph compares the overhead of PerfTracker with cProfile, another popular performance tracking package.
![Performance Comparison](https://github.com/vertyco/perftracker/blob/master/.github/ASSETS/overhead_comparison.png?raw=true)
During this test, PerfTracker consistently has less overhead than cProfile. The code used for this comparison can be found [Here](https://github.com/vertyco/perftracker/blob/master/overhead_comparison.py)
## Contributing
We welcome contributions to PerfTracker. If you have a feature request, bug report, or want to improve the code, please feel free to submit a Pull Request.
## License
PerfTracker is licensed under the terms of the MIT license. This means you are free to use, modify, and distribute the code, as long as you include the original copyright and license notice.
Raw data
{
"_id": null,
"home_page": "https://github.com/vertyco/perftracker",
"name": "perftracker",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": "",
"keywords": "",
"author": "vertyco",
"author_email": "alex.c.goble@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/54/52/ccc974077b2128c51cddb8e1d5cc65e1730ba6e65938d2e4bd4627e0ca39/perftracker-1.4.0.tar.gz",
"platform": null,
"description": "# PerfTracker\r\n\r\nPerfTracker is a erformance tracking package designed to assist developers in monitoring and tracking the execution time of their functions. It provides a straightforward and efficient way to measure function performance, enabling you to optimize your code effectively.\r\n\r\n[![badge](https://img.shields.io/pypi/v/perftracker)](https://pypi.org/project/perftracker/)\r\n[![badge](https://img.shields.io/pypi/dm/perftracker)](https://pypi.org/project/perftracker/)\r\n\r\n## Features\r\n\r\n- **Ease of Use**: Simply add a decorator to your functions.\r\n- **Flexibility**: Can be used without decorator for manual tracking.\r\n- **Detailed Statistics**: PerfTracker provides comprehensive statistics about your function's performance. It allows you to get the execution times and calculate the average calls per minute over a certain period. This information can be crucial in identifying bottlenecks in your code and optimizing it.\r\n- **No Dependencies**: PerfTracker does not require any 3rd party packages to function.\r\n- **Debug Logging**: Logs function execution deltas in real time.\r\n ```\r\n [09:48:58] DEBUG [perftracker] levelup.levelup.message_handler took 0.0017ms to complete.\r\n [09:49:18] DEBUG [perftracker] levelup.levelup.save_cache took 0.001099ms to complete.\r\n ```\r\n\r\n## Disclaimer\r\n\r\nThis package uses a global variable `_perf` for the performance model. It uses a key schema\r\nof `module_name.function_name` to avoid interference when multiple packages use it for tracking.\r\n\r\n## Installation\r\n\r\nTo install PerfTracker using pip, Run the following command in your terminal:\r\n\r\n```bash\r\npip install perftracker\r\n```\r\n\r\n### Methods\r\n\r\nPerfTracker provides several methods to track and retrieve function performance data:\r\n\r\n- `@perf(max_entries=None)`: A decorator to measure and record the execution time of a function. If `max_entries` is set, it will limit the number of records kept for the function to this value.\r\n- `get_stats()`: Returns the current Performance instance, which contains all recorded performance data.\r\n- `Performance.add(function, exe_time, max_entries=None)`: Adds an execution time record for a function. You can use this method to manually add execution time records.\r\n- `Performance.get(function)`: Returns the execution time records for a function. This can be useful if you want to analyze the performance data further.\r\n- `Performance.cpm(function, time_delta)`: Calculates the average calls per minute (CPM) of a function over a certain period. This can give you an idea of how frequently a function is called.\r\n- `Performance.avg_time(function, time_delta)`: Calculate the average time a function takes to execute over a certain period. This can help you identify slow functions that may need optimization.\r\n\r\n## Usage\r\n\r\nUsing PerfTracker is straightforward. Here are some examples:\r\n\r\n### Basic Usage\r\n\r\n```python\r\nfrom perftracker import perf, get_stats\r\n\r\n@perf(max_entries=100)\r\ndef my_function():\r\n # Your code here...\r\n\r\n# Get performance statistics\r\nstats = get_stats()\r\n```\r\n\r\n### Retrieving Execution Time Records\r\n\r\n```python\r\nfrom perftracker import perf, get_stats\r\n\r\n@perf(max_entries=100)\r\ndef my_function():\r\n # Your code here...\r\n\r\n# Get performance statistics\r\nstats = get_stats()\r\n\r\n# Retrieve execution time records\r\nrecords = stats.get(my_function)\r\n```\r\n\r\n### Calculating Calls Per Minute\r\n\r\n```python\r\nfrom perftracker import perf, get_stats\r\nfrom datetime import timedelta\r\n\r\n@perf(max_entries=100)\r\ndef my_function():\r\n # Your code here...\r\n\r\n# Get performance statistics\r\nstats = get_stats()\r\n\r\n# Calculate calls per minute for the last hour\r\ncpm = stats.cpm(my_function, timedelta(hours=1))\r\n```\r\n\r\n### Tracking Things Manually\r\n\r\n```python\r\nfrom perftracker import get_stats\r\nfrom time import perf_counter\r\n\r\ndef some_function():\r\n stats = get_stats()\r\n start_time = perf_counter()\r\n\r\n ... # Some code that takes time...\r\n\r\n end_time = perf_counter()\r\n delta = (end_time - start_time) * 1000 # Use milliseconds\r\n\r\n # Add time manually, the 'add' method can take strings too\r\n stats.add(\"my_custom_function_key\", delta)\r\n```\r\n\r\n### Full Usage\r\n\r\n```python\r\nfrom perftracker import perf, get_stats\r\nfrom datetime import timedelta\r\nfrom time import sleep\r\nimport random\r\n\r\n@perf(max_entries=100)\r\ndef my_function():\r\n # Your code here...\r\n\r\n# Run the code a few times\r\nfor _ in range(10):\r\n my_function()\r\n sleep(random.random())\r\n\r\n# Get performance statistics\r\nstats = get_stats()\r\n\r\n# Get a list of Record objects (Record represents when a function was called)\r\nrecords = stats.get(my_function)\r\n\r\n# Get first time the function was called\r\nrecord = records[0]\r\n\r\n# (float) Time this particular entry took to execute in ms\r\nexecution_time = record.exe_time\r\n\r\n# (datetime.datetime) in UTC timezone naive, the time when this entry was created\r\ntimestamp = record.timestamp\r\n\r\n# Calls per minute (float)\r\ncpm = stats.cpm(my_function)\r\n\r\n# Average execution time (float)\r\navg_exe_time = stats.avg_time(my_function)\r\n```\r\n\r\n### Discord Bot Cog Usage\r\n\r\nPerfTracker can also be used in a Discord bot environment to help you track down bottlenecks in your bot's performance. Here is an example of how you can use PerfTracker in a Discord bot cog:\r\n\r\n```python\r\nfrom discord.ext import commands\r\nfrom perftracker import perf, get_stats\r\n\r\nclass MyCog(commands.Cog):\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @perf(max_entries=100)\r\n async def slow_function(self, ctx):\r\n # Your sussy code here...\r\n\r\n @commands.command()\r\n async def performance(self, ctx):\r\n stats = get_stats()\r\n records = stats.get(self.slow_function)\r\n if records:\r\n avg_time = stats.avg_time(self.slow_function)\r\n await ctx.send(f\"Average execution time for slow_function: {avg_time}ms\")\r\n else:\r\n await ctx.send(f\"No performance records found for {function_name}\")\r\n\r\ndef setup(bot):\r\n bot.add_cog(MyCog(bot))\r\n```\r\n\r\nIn this example, `slow_function` is a function in a Discord bot cog that is tracked by PerfTracker. The `performance` command can be used to retrieve the average execution time of the specific command.\r\n\r\nYou can replace `slow_function` with any function in your bot that you want to track. The performance statistics are stored in memory and will be lost when the bot is restarted.\r\n\r\nPlease note that this example assumes you have basic knowledge of how to create and use cogs in a Discord bot. If you are unfamiliar with this, you can read the [Discord.py Cogs guide](https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html).\r\n\r\n## Performance Comparison\r\n\r\nPerfTracker is designed to have minimal overhead, allowing you to monitor your program's performance without significantly affecting its execution time. The following graph compares the overhead of PerfTracker with cProfile, another popular performance tracking package.\r\n\r\n![Performance Comparison](https://github.com/vertyco/perftracker/blob/master/.github/ASSETS/overhead_comparison.png?raw=true)\r\n\r\nDuring this test, PerfTracker consistently has less overhead than cProfile. The code used for this comparison can be found [Here](https://github.com/vertyco/perftracker/blob/master/overhead_comparison.py)\r\n\r\n## Contributing\r\n\r\nWe welcome contributions to PerfTracker. If you have a feature request, bug report, or want to improve the code, please feel free to submit a Pull Request.\r\n\r\n## License\r\n\r\nPerfTracker is licensed under the terms of the MIT license. This means you are free to use, modify, and distribute the code, as long as you include the original copyright and license notice.\r\n",
"bugtrack_url": null,
"license": "",
"summary": "PerfTracker is a lightweight function performance monitoring framework",
"version": "1.4.0",
"project_urls": {
"Homepage": "https://github.com/vertyco/perftracker"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "5452ccc974077b2128c51cddb8e1d5cc65e1730ba6e65938d2e4bd4627e0ca39",
"md5": "682562c66b835b6bf74481fbbb19fbe8",
"sha256": "3ade998635adeff5c3921ce66c22d838e279459a9d193a09203aa5e156a89de2"
},
"downloads": -1,
"filename": "perftracker-1.4.0.tar.gz",
"has_sig": false,
"md5_digest": "682562c66b835b6bf74481fbbb19fbe8",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 8315,
"upload_time": "2024-01-06T20:01:12",
"upload_time_iso_8601": "2024-01-06T20:01:12.671893Z",
"url": "https://files.pythonhosted.org/packages/54/52/ccc974077b2128c51cddb8e1d5cc65e1730ba6e65938d2e4bd4627e0ca39/perftracker-1.4.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-01-06 20:01:12",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "vertyco",
"github_project": "perftracker",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "perftracker"
}