{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n============================================================================\nExample: decorating specified methods of a custom class with timer decorator\n============================================================================\n\nThis example shows how to decorate methods of a custom class with a timer\ndecorator.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import time\n\nfrom pydeco import Decorator, MethodsDecorator"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Create timer decorator\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class Timer(Decorator):\n    \"\"\"Timer decorator.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self.run = 0\n        self.run_by_func = dict()\n        self.total_runtime = 0\n        Decorator.__init__(self, *args, **kwargs)\n\n    def __repr__(self):\n        \"\"\"Return the string representation.\"\"\"\n        return ('Timer(run={}, run_by_func={}, total_runtime={:2.2f} ms)'\n                .format(self.run, self.run_by_func, self.total_runtime))\n\n    def wrapper(self, instance, func, *args, **kwargs):\n        \"\"\"Wrap input instance method with runtime measurement.\"\"\"\n        # increment run attributes\n        self.run += 1\n        if func.__name__ not in self.run_by_func:\n            self.run_by_func[func.__name__] = 1\n        else:\n            self.run_by_func[func.__name__] += 1\n\n        # save current time\n        ts = time.time()\n\n        # call `func` on inputs\n        outs = func(instance, *args, **kwargs)\n\n        # compute elapsed time\n        te = time.time()\n        runtime = (te - ts) * 1000\n        # Update total runtime of timer\n        self.total_runtime += runtime\n\n        print('[Log] runtime {!r} : {:2.2f} ms'.format(func.__name__, runtime))\n\n        # return outputs of `func`\n        return outs"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Create custom class and decorate some of its methods with :class:`Timer`\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# instantiate decorator\ntimer = Timer()\n\n\n# create class :class:`MyClass` and decorate `method_1` and `method_2` with\n# decorator `timer`\n@MethodsDecorator(mapping={timer: ['method_1', 'method_2']})\nclass MyClass():\n    \"\"\"Custom class.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        pass\n\n    def method_1(self, sleep=.01, **kwargs):\n        print('Running \\'method_1\\' (sleep {:2.2f} ms)'.format(sleep * 1000))\n        time.sleep(sleep)\n\n    def method_2(self, sleep=.02, **kwargs):\n        print('Running \\'method_2\\' (sleep {:2.2f} ms)'.format(sleep * 1000))\n        time.sleep(sleep)\n\n    def method_3(self, sleep=.03, **kwargs):\n        print('Running \\'method_3\\' (sleep {:2.2f} ms)'.format(sleep * 1000))\n        time.sleep(sleep)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Run tests\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# instantiate the class\ninstance = MyClass()\n\n# run methods\ninstance.method_1()\ninstance.method_2()\ninstance.method_3()\n\nprint(timer)\n\n# deactivate timer for all methods of linked decorated instances\ntimer.deactivate()\n\n# run methods\ninstance.method_1()\ninstance.method_2()\ninstance.method_3()\n\nprint(timer)\n\n# activate timer back for all methods of linked decorated instances\ntimer.activate()\n\n# run methods\ninstance.method_1()\ninstance.method_2()\ninstance.method_3()\n\nprint(timer)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}