diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..62204cc --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,15 @@ +version: 2 # use CircleCI 2.0 +jobs: # A basic unit of work in a run + build: # runs not using Workflows must have a `build` job as entry point + # directory where steps are run + working_directory: ~/bench_utils + docker: # run the steps with Docker + # CircleCI Python images available at: https://hub.docker.com/r/circleci/python/ + - image: circleci/python:3.8 + steps: # steps that comprise the `build` job + - checkout # check out source code to working directory + - run: make create_env env=venv + - run: source venv/bin/activate + - run: make dist + - run: make tests +# - run: make release diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml new file mode 100644 index 0000000..b25904c --- /dev/null +++ b/.github/workflows/python-publish.yml @@ -0,0 +1,24 @@ +name: Upload Python Package + +on: + release: + types: [created] + +jobs: + deploy: + runs-on: ubuntu-20.04 + + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install setuptools wheel twine + - name: Build and publish + env: + TWINE_USERNAME: __token__ + TWINE_PASSWORD: ${{ secrets.GITHUBACTIONS }} + run: | + python setup.py sdist bdist_wheel + twine upload dist/* \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..392e377 --- /dev/null +++ b/.gitignore @@ -0,0 +1,141 @@ +*.bak +.gitattributes +.last_checked +.gitconfig +*.bak +*.log +*~ +~* +_tmp* +tmp* +tags + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +#dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +.vscode +*.swp + +# osx generated files +.DS_Store +.DS_Store? +.Trashes +ehthumbs.db +Thumbs.db +.idea + +# pytest +.pytest_cache + +# tools/trust-doc-nbs +docs_src/.last_checked + +# symlinks to fastai +docs_src/fastai +tools/fastai + +# link checker +checklink/cookies.txt + +# .gitconfig is now autogenerated +.gitconfig + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..aac956e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,22 @@ +# How to contribute + +## Did you find a bug? + +* Ensure the bug was not already reported by searching on GitHub under Issues. +* If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring. +* Be sure to add the complete error messages. + +#### Did you write a patch that fixes a bug? + +* Open a new GitHub pull request with the patch. +* Ensure that your PR includes a test that fails without your patch, and pass with it. +* Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable. + +## PR submission guidelines + +* Keep each PR focused. While it's more convenient, do not combine several unrelated fixes together. Create as many branches as needing to keep each PR focused. +* Do not mix style changes/fixes with "functional" changes. It's very difficult to review such PRs and it most likely get rejected. +* Do not add/remove vertical whitespace. Preserve the original style of the file you edit as much as you can. +* Do not turn an already submitted PR into your development playground. If after you submitted PR, you discovered that more work is needed - close the PR, do the required work and then submit a new PR. Otherwise each of your commits requires attention from maintainers of the project. +* If, however, you submitted a PR and received a request for changes, you should proceed with commits inside that PR, so that the maintainer can see the incremental fixes and won't need to review the whole PR again. In the exception case where you realize it'll take many many commits to complete the requests, then it's probably best to close the PR, do the work and then submit it again. Use common sense where you'd choose one way over another. + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..5c0e7ce --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,5 @@ +include settings.ini +include LICENSE +include CONTRIBUTING.md +include README.md +recursive-exclude * __pycache__ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..2a04ec6 --- /dev/null +++ b/Makefile @@ -0,0 +1,86 @@ +.ONESHELL: +SHELL:=/bin/bash +PYTHON_VERSION:=3.8 + +# You can use either venv (venv) or conda env +# by specifying the correct argument (env=) +ifeq ($(env),venv) + # Use Conda + BASE=venv + BIN=$(BASE)/bin + CREATE_COMMAND="python$(PYTHON_VERSION) -m venv $(BASE)" + DELETE_COMMAND="rm -rf $(BASE)" + ACTIVATE_COMMAND="source venv/bin/activate" + DEACTIVATE_COMMAND="deactivate" +else + # Use Conda + BASE=~/anaconda3/envs/bench_utils + BIN=$(BASE)/bin + CREATE_COMMAND="conda create --prefix $(BASE) python=$(PYTHON_VERSION) -y" + DELETE_COMMAND="conda env remove -p $(BASE)" + ACTIVATE_COMMAND="conda activate -p $(BASE)" + DEACTIVATE_COMMAND="conda deactivate" +endif + +all: + $(MAKE) help +help: + @echo + @echo "-------------------------------------------------------------------------------------------" + @echo " DISPLAYING HELP " + @echo "-------------------------------------------------------------------------------------------" + @echo "Run: make [env=]" + @echo + @echo "make help" + @echo " Display this message" + @echo "make release [env=]" + @echo " Run pypi conda_release fastrelease_bump_version" + @echo "make release_requirements [env=]" + @echo " Install fastrelease twine and conda-build" + @echo "make pypi [env=]" + @echo " Run dist and upload using twine" + @echo "make dist [env=]" + @echo " Clean and create bdist and wheel" + @echo "make clean [env=]" + @echo " Delete all './build ./dist ./*.pyc ./*.tgz ./*.egg-info' files" +# @echo "make tests [env=]" +# @echo " Run all tests" + @echo "make create_env [env=]" + @echo " Create a new conda env or venv for the specified python version" + @echo "make delete_env [env=]" + @echo " Delete the current conda env or venv" + @echo "-------------------------------------------------------------------------------------------" +release: + $(MAKE) release_requirements + $(MAKE) pypi + #$(MAKE) conda_release + #fastrelease_bump_version +release_test: + $(MAKE) release_requirements + $(MAKE) pypi_test +release_requirements: + $(BIN)/pip install fastrelease twine conda-build +pypi: + $(MAKE) dist + twine upload --repository pypi dist/* +pypi_test: + $(MAKE) dist_test + twine upload --repository pypitest dist/* --verbose +conda_release: + fastrelease_conda_package --upload_user drkostas +dist: + $(MAKE) clean + python setup.py sdist bdist_wheel +dist_test: + $(MAKE) clean + python setup.py sdist bdist_wheel --test +clean: + python setup.py clean +tests: + python setup.py test +create_env: + @eval $(CREATE_COMMAND) +delete_env: + @eval $(DELETE_COMMAND) + +.PHONY: all help release conda_release pypi clean dist tests create_env delete_env dist_test pypi_test release_test \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..3bd1813 --- /dev/null +++ b/README.md @@ -0,0 +1,115 @@ +# Benchmark Utilities + +[![GitHub license](https://img.shields.io/badge/license-Apache-blue.svg)](https://raw.githubusercontent.com/drkostas/bench-utils/master/LICENSE) + +## About + +A collection of benchmarking +tools. [PYPI Package](https://pypi.org/manage/project/bench-utils/releases/) + +## Table of Contents + ++ [Using the library](#using) + + [Installing and using the library](#install_use) ++ [Manually install the library](#manual_install) + + [Prerequisites](#configuration) + + [Install the requirements](#installing_req) ++ [License](#license) + +## Using the library + +### Installing and using the library + +First, you need to install the library either using pip: + +```shell +$ pip install bench_utils +``` + +Then, import it and use it like so: + +```python +from bench_utils import timeit, profileit + +# --- Timeit --- # +# Context Manager +with timeit(): + # A code block + pass + + +@timeit() +def my_func(): + # Function code + pass + + +# --- Profileit --- # +# Context Manager +with profileit(): + # A code block + pass + + +@profileit() +def my_func(): + # Function code + pass +``` + +For more advanced examples +check [example_timeit.py](https://raw.githubusercontent.com/drkostas/bench-utils/master/example_timeit.py) +and [example_profileit.py](https://raw.githubusercontent.com/drkostas/bench-utils/master/example_profileit.py) +. + +## Manually install the library + +These instructions will get you a copy of the project up and running on your local machine for +development and testing purposes. See deployment for notes on how to deploy the project on a live +system. + +### Prerequisites + +You need to have a machine with +[anaconda](https://docs.conda.io/projects/conda/en/latest/user-guide/install/index.html) installed and +any Bash based shell (e.g. zsh) installed. + +```ShellSession + +$ conda -V +conda 4.10.1 + +$ echo $SHELL +/usr/bin/zsh + +``` + +### Install the requirements + +All the installation steps are being handled by +the [Makefile](https://raw.githubusercontent.com/drkostas/bench-utils/master/Makefile). First, create a +file called `~/.pypirc` with your pypi login details, as follows: + +``` +[pypi] +username = your_pypi_username +password = your_pypi_password +``` + +Then, modify the python version and everything else you need in +the [settings.ini](https://raw.githubusercontent.com/drkostas/bench-utils/master/settings.ini). + +Finally, execute the following commands: + +```ShellSession +$ make create_env +$ conda activate bench_utils +$ make release +``` + +## License + +This project is licensed under the MIT License - see +the [LICENSE](https://raw.githubusercontent.com/drkostas/bench-utils/master/LICENSE) file for details. + +Buy Me A Coffee diff --git a/bench_utils/__init__.py b/bench_utils/__init__.py new file mode 100644 index 0000000..319db73 --- /dev/null +++ b/bench_utils/__init__.py @@ -0,0 +1,6 @@ +from .timeit import timeit +from .profileit import profileit + +__author__ = "drkostas" +__email__ = "georgiou.kostas94@gmail.com" +__version__ = "0.0.1" diff --git a/bench_utils/profileit.py b/bench_utils/profileit.py new file mode 100644 index 0000000..44bab41 --- /dev/null +++ b/bench_utils/profileit.py @@ -0,0 +1,114 @@ +from contextlib import ContextDecorator +from typing import Callable, IO, List +from io import StringIO +from functools import wraps +import cProfile +import pstats + +from termcolor_logger import ColorLogger + +profile_logger = ColorLogger('Profileit', 'white') + + +class profileit(ContextDecorator): + custom_print: str + profiler: cProfile.Profile + stream: StringIO + sort_by: str + keep_only_these: List + fraction: float + skip: bool + profiler_output: str + file: IO + + def __init__(self, **kwargs): + """Decorator/ContextManager for profiling functions and code blocks + + Args: + custom_print: Custom print string. When used as decorator it can also be formatted using + `func_name`, `args`, and {0}, {1}, .. to reference the function's + first, second, ... argument. + sort_by: pstats sorting column + profiler_output: Filepath where to save the profiling results (.o file) + keep_only_these: List of strings - grep on the profiling output and print only lines + containing any of these strings + fraction: pstats.print_stats() fraction argument + skip: If True, don't time this time. Suitable when inside loops + file: Write the timing output to a file too + """ + + self.profiler = cProfile.Profile() + self.stream = StringIO() + self.sort_by = 'stdname' + self.keep_only_these = [] + self.fraction = 1.0 + self.skip = False + self.__dict__.update(kwargs) + + def __call__(self, func: Callable): + """ This is called only when invoked as a decorator + + Args: + func: The method to wrap + """ + + @wraps(func) + def profiled(*args, **kwargs): + with self._recreate_cm(): + self.func_name = func.__name__ + self.args = args + self.kwargs = kwargs + self.all_args = (*args, *kwargs.values()) if kwargs != {} else args + return func(*args, **kwargs) + + return profiled + + def __enter__(self, *args, **kwargs): + if not self.skip: + self.profiler.enable() + return self + + def __exit__(self, type, value, traceback): + if self.skip: + return + + self.profiler.disable() + ps = pstats.Stats(self.profiler, stream=self.stream).sort_stats(self.sort_by) + ps.print_stats(self.fraction) + + # If used as a decorator + if hasattr(self, 'func_name'): + if not hasattr(self, 'custom_print'): + print_string = 'Func: {func_name!r} with args: {args!r} profiled:' + else: + print_string = self.custom_print + print_string = print_string.format(*self.args, func_name=self.func_name, + args=self.all_args, + **self.kwargs) + # If used as contextmanager + else: + if not hasattr(self, 'custom_print'): + print_string = 'Code block profiled:' + else: + print_string = self.custom_print + + # Get Profiling results + prof_res = self.stream.getvalue() + if len(self.keep_only_these) > 0: + # Keep only lines containing the specified words + prof_res_list = [line for line in prof_res.split('\n') + if any(keep_word in line for keep_word in self.keep_only_these)] + prof_res = '\n'.join(prof_res_list) + + # Print to file if requested + if hasattr(self, 'file'): + self.file.write(print_string) + self.file.write("\n%s" % prof_res) + + # Save profiler output to a file if requested + if hasattr(self, 'profiler_output'): + self.profiler.dump_stats(self.profiler_output) + + # Actual Print + profile_logger.info(print_string) + profile_logger.info("%s", prof_res) diff --git a/bench_utils/timeit.py b/bench_utils/timeit.py new file mode 100644 index 0000000..f734a78 --- /dev/null +++ b/bench_utils/timeit.py @@ -0,0 +1,81 @@ +from contextlib import ContextDecorator +from typing import Callable, IO, Union +from functools import wraps +from time import time + +from termcolor_logger import ColorLogger + +time_logger = ColorLogger('Timeit', 'white') + + +class timeit(ContextDecorator): + custom_print: str + skip: bool + total: Union[float, None] + internal_only: bool + file: IO + + def __init__(self, **kwargs): + """Decorator/ContextManager for counting the execution times of functions and code blocks + + Args: + custom_print: Custom print string Use {duration} to reference the running time. + When used as decorator it can also be formatted using + `func_name`, `args`, and {0}, {1}, .. to reference the function's + first, second, ... argument. + skip: If True, don't time this time. Suitable when inside loops + file: Write the timing output to a file too + """ + + self.total = None + self.skip = False + self.internal_only = False + self.__dict__.update(kwargs) + + def __call__(self, func: Callable): + """ This is called only when invoked as a decorator + + Args: + func: The method to wrap + """ + + @wraps(func) + def timed(*args, **kwargs): + with self._recreate_cm(): + self.func_name = func.__name__ + self.args = args + self.kwargs = kwargs + self.all_args = (*args, *kwargs.values()) if kwargs != {} else args + return func(*args, **kwargs) + + return timed + + def __enter__(self, *args, **kwargs): + if not self.skip: + self.ts = time() + return self + + def __exit__(self, type, value, traceback): + if self.skip: + return + + self.te = time() + self.total = self.te - self.ts + if hasattr(self, 'func_name'): + if not hasattr(self, 'custom_print'): + print_string = 'Func: {func_name!r} with args: {args!r} took: {duration:2.5f} sec(s)' + else: + print_string = self.custom_print + time_logger.info(print_string.format(*self.args, func_name=self.func_name, + args=self.all_args, + duration=self.total, + **self.kwargs)) + else: + if not hasattr(self, 'custom_print'): + print_string = 'Code block took: {duration:2.5f} sec(s)' + else: + print_string = self.custom_print + if hasattr(self, 'file'): + self.file.write(print_string.format(duration=self.total)) + if not self.internal_only: + time_logger.info(print_string.format(duration=self.total)) diff --git a/dist/bench_utils-0.0.1-py3-none-any.whl b/dist/bench_utils-0.0.1-py3-none-any.whl new file mode 100644 index 0000000..1d024f1 Binary files /dev/null and b/dist/bench_utils-0.0.1-py3-none-any.whl differ diff --git a/dist/bench_utils-0.0.1.tar.gz b/dist/bench_utils-0.0.1.tar.gz new file mode 100644 index 0000000..4133273 Binary files /dev/null and b/dist/bench_utils-0.0.1.tar.gz differ diff --git a/example_profileit.py b/example_profileit.py new file mode 100644 index 0000000..9369f46 --- /dev/null +++ b/example_profileit.py @@ -0,0 +1,53 @@ +# pip install bench-utils +from bench_utils import profileit +import time + + +# --- Timeit as a decorator --- # + +# Set custom print and use the function name and arguments as you want +@profileit(custom_print='Running {func_name} function with arguments {args} ({0} and {1})') +def run_something(a=1, b=2): + for i in range(b): + run_something_2(a) + a += 1 + return "ok" + + +def run_something_2(c=3): + return c ** 2 + + +run_something(3, 5) + +# --- Timeit as a Context Manager --- # + +# Set custom print and use the duration argument as you want +# the `skip` argument is for skipping the timeit when desired +with profileit(custom_print='Code Block Time: {duration:2.5f} sec(s)', skip=False): + for _ in range(2): + time.sleep(0.1) + +# The `internal_only` argument is for not printing the timeit but storing the duration variable +# which can be accessed and saved +timeit_without_print = profileit(internal_only=True) +with timeit_without_print: + for _ in range(3): + time.sleep(0.1) +profiler_obj = timeit_without_print.profiler +# print(timeit_total) + +# The `file` argument is for saving the output in a file (e.g. when using a logger) +# `k_words` is used to include only pstats that contain these words +# `sort_by` is to select the sorting argument (pstat column) +file = open('tmp.log', 'w+') +profiler_output = 'profiler_output.log' +keep_only_these = ['bench_utils'] +sort_by = 'tottime' +custom_print = f'Profiling Code block - skipping: ' +with profileit(file=file, profiler_output=profiler_output, + keep_only_these=keep_only_these, + custom_print=custom_print, sort_by=sort_by, internal_only=True): + run_something_2(1) + run_something_2(4) +# See tmp.log diff --git a/example_timeit.py b/example_timeit.py new file mode 100644 index 0000000..2b1752e --- /dev/null +++ b/example_timeit.py @@ -0,0 +1,45 @@ +# pip install bench-utils +from bench_utils import timeit +import time + + +# --- Timeit as a decorator --- # + +# Set custom print and use the function name and arguments as you want +@timeit(custom_print='Running {func_name} function with arguments {args} ({0} and {1})') +def run_something(a=1, b=2): + for i in range(b): + run_something_2(a) + a += 1 + return "ok" + + +def run_something_2(c=3): + return c ** 2 + + +run_something(3, 5) + +# --- Timeit as a Context Manager --- # + +# Set custom print and use the duration argument as you want +# the `skip` argument is for skipping the timeit when desired +with timeit(custom_print='Code Block Time: {duration:2.5f} sec(s)', skip=False): + for _ in range(2): + time.sleep(0.1) + +# The `internal_only` argument is for not printing the timeit but storing the duration variable +# which can be accessed and saved +timeit_without_print = timeit(internal_only=True) +with timeit_without_print: + for _ in range(3): + time.sleep(0.1) +timeit_total = timeit_without_print.total +# print(timeit_total) + +# The `file` argument is for saving the output in a file (e.g. when using a logger) +file = open('tmp.log', 'w+') +with timeit(custom_print='Printing in file - Code Block Time: {duration:2.5f} sec(s)', file=file): + for _ in range(2): + time.sleep(0.1) +# See tmp.log diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..4a24035 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +termcolor-logger>=0.0.1 diff --git a/settings.ini b/settings.ini new file mode 100644 index 0000000..e3984b5 --- /dev/null +++ b/settings.ini @@ -0,0 +1,38 @@ +[DEFAULT] +# All sections below are required unless otherwise specified +host = github +lib_name = bench_utils +user = drkostas +description = A collection of benchmarking tools. +keywords = benchmark, bench, profiling, timing, tools, utils +author = Kostas Georgiou +author_email = georgiou.kostas94@gmail.com +copyright = Kostas Georgiou +branch = master +version = 0.0.1 +testing_version = 0.0.1 +min_python = 3.6 +audience = Developers +language = English +# Add licenses and see current list in `setup.py` +license = apache2 +# From 1-7: Pre-Alpha Alpha Beta Production Mature Inactive +status = 4 + +# Optional. Same format as setuptools requirements +requirements = requirements.txt +data_files = +# Optional. Same format as setuptools console_scripts +# console_scripts = +# Optional. Same format as setuptools dependency-links +# dep_links = + +# Values of the form `%(foo)s` are automatically replaced with the value of `foo` +lib_path = %(lib_name)s + +git_url = https://github.com/%(user)s/%(lib_name)s/tree/%(branch)s/ +# For Enterprise Github use: +# repo_name = your-repo +# company_name = your-company +# git_url = https://github.%(company_name)s.com/%(repo_name)s/%(lib_name)s/tree/%(branch)s/ + diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..4b9c141 --- /dev/null +++ b/setup.py @@ -0,0 +1,84 @@ +import os +import sys +from pkg_resources import parse_version +from configparser import ConfigParser +import setuptools + +assert parse_version(setuptools.__version__) >= parse_version('36.2') + +# For the cases you want a different package to be installed on local and prod environments +LOCAL_ARG = '--test' +if LOCAL_ARG in sys.argv: + index = sys.argv.index(LOCAL_ARG) # Index of the local argument + sys.argv.pop(index) # Removes the local argument in order to prevent the setup() error + testing = True +else: + testing = False + + +class CleanCommand(setuptools.Command): + """Custom clean command to tidy up the project root.""" + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + os.system('rm -vrf ./build ./dist ./*.pyc ./*.tgz ./*.egg-info') + + +# note: all settings are in settings.ini; edit there, not here +config = ConfigParser(delimiters=['=']) +config.read('settings.ini') +cfg = config['DEFAULT'] +if testing: + lib_version = cfg['testing_version'] +else: + lib_version = cfg['version'] + +cfg_keys = 'description keywords author author_email'.split() +expected = cfg_keys + "lib_name user branch license status min_python audience language".split() +for o in expected: + assert o in cfg, "missing expected setting: {}".format(o) +setup_cfg = {o: cfg[o] for o in cfg_keys} +licenses = {'apache2': ('Apache Software License 2.0', 'OSI Approved :: Apache Software License')} +statuses = ['1 - Planning', '2 - Pre-Alpha', '3 - Alpha', '4 - Beta', + '5 - Production/Stable', '6 - Mature', '7 - Inactive'] +py_versions = '2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8'.split() +with open(cfg.get('requirements', '')) as f: + requirements = f.readlines() +data_files = cfg['data_files'].split() +lic = licenses[cfg['license']] +min_python = cfg['min_python'] + +setuptools.setup( + name=cfg['lib_name'], + license=lic[0], + classifiers=['Development Status :: ' + statuses[int(cfg['status'])], + 'Intended Audience :: ' + cfg['audience'].title(), + 'License :: ' + lic[1], + 'Natural Language :: ' + cfg['language'].title()] + + ['Programming Language :: Python :: ' + o for o in + py_versions[py_versions.index(min_python):]], + url=cfg['git_url'], + packages=setuptools.find_packages(), + include_package_data=True, + data_files=[('', data_files)], + test_suite='tests', + install_requires=requirements, + setup_requires=requirements, + tests_require=requirements, + cmdclass={ + 'clean': CleanCommand, + }, + dependency_links=cfg.get('dep_links', '').split(), + python_requires='>=' + cfg['min_python'], + long_description=open('README.md').read(), + long_description_content_type='text/markdown', + zip_safe=False, + entry_points={'console_scripts': cfg.get('console_scripts', '').split()}, + version=lib_version, + **setup_cfg)