Skip to content

Commit

Permalink
Merge pull request #4 from boris-42/add_tracing_code_base
Browse files Browse the repository at this point in the history
Add tracing code base
  • Loading branch information
boris-42 committed Apr 2, 2015
2 parents 513c974 + 713f749 commit 04b8651
Show file tree
Hide file tree
Showing 11 changed files with 672 additions and 13 deletions.
26 changes: 23 additions & 3 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,26 @@
==============================
Profimp - python import tracer
==============================
===============================
Profimp - python imports tracer
===============================


Profimp allows you to trace imports of your code.

This lib should be used to simplify optimization of imports in your code.
At least you will find what consumes the most part of time and do the
right decisions.

Syntax:

.. code-block::
profimp [import_module_line]
Samples:

.. code-block::
profimp "import re"
or
profimp "from somemoudle import something"
23 changes: 21 additions & 2 deletions doc/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,27 @@
under the License.


Profimp - python import tracer
==============================
Profimp - python imports tracer
===============================

Profimp allows you to trace imports of your code.

This lib should be used to simplify optimization of imports in your code.
At least you will find what consumes the most part of time and do the
right decisions.

Syntax:

.. code-block::
profimp [import_module_line]
Samples:

.. code-block::
profimp "import re"
or
profimp "from somemoudle import something"
47 changes: 46 additions & 1 deletion profimp/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,54 @@
# License for the specific language governing permissions and limitations
# under the License.

from __future__ import print_function

import sys

from profimp import reports
from profimp import tracer


HELP_MESSAGE = """
Profimp allows you to trace imports of your code.
This lib should be used to simplify optimization of imports in your code.
At least you will find what consumes the most part of time and do the
right decisions.
Syntax:
profimp [import_module_line]
Samples:
profimp "import re"
or
profimp "from somemoudle import something"
"""


def print_help():
print(HELP_MESSAGE)


def trace_module(import_line):
root_pt = tracer.init_stack()
with tracer.patch_import():
exec(import_line)
return root_pt


def main():
return "Hello world"
if len(sys.argv) == 1:
print_help()
elif len(sys.argv) == 2:
report = reports.to_json(trace_module(sys.argv[1]))
sys.stdout.write(report)
else:
print_help()
raise SystemExit("Wrong input arguments: %s" % sys.argv)


if __name__ == "__main__":
main()
9 changes: 3 additions & 6 deletions tests/unit/test_noop.py → profimp/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,8 @@
# License for the specific language governing permissions and limitations
# under the License.

from tests.unit import test
import json


class NoopTestCase(test.TestCase):
"""Test case base class for all unit tests."""

def test_noop(self):
self.assertEqual(4, 2 + 2)
def to_json(results):
return json.dumps(results.to_dict(), indent=2)
98 changes: 98 additions & 0 deletions profimp/tracer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Copyright 2015: Boris Pavlovic
# All Rights Reserved.
#
# 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.

import contextlib
import time

from six.moves import builtins


class TracePoint(object):

def __init__(self, import_line, level=0):
self.started_at = 0
self.finished_at = 0
self.import_line = import_line
self.level = level
self.children = []

def __enter__(self):
self.start()
return self

def __exit__(self, etype, value, traceback):
self.stop()

def to_dict(self):

result = {
"started_at": self.started_at,
"finished_at": self.finished_at,
"duration": (self.finished_at - self.started_at) * 1000,
"import_line": self.import_line,
"level": self.level,
"children": []
}

for child in self.children:
result["children"].append(child.to_dict())

return result

def start(self):
self.started_at = time.time()

def stop(self):
self.finished_at = time.time()

def add_child(self, child):
self.children.append(child)
child.level = self.level + 1


TRACE_STACK = []


def init_stack():
global TRACE_STACK
TRACE_STACK = [TracePoint("root", 0)]
return TRACE_STACK[0]


@contextlib.contextmanager
def patch_import():
old_import = builtins.__import__
builtins.__import__ = _traceit(builtins.__import__)
yield
builtins.__import__ = old_import


def _traceit(f):
def w(*args, **kwargs):
import_line = ""

if len(args) > 3 and args[3]:
import_line = "from %s import %s" % (args[0], ", ".join(args[3]))
else:
import_line = "import %s" % args[0]

with TracePoint(import_line) as trace_pt:
TRACE_STACK[-1].add_child(trace_pt)
TRACE_STACK.append(trace_pt)
try:
return f(*args, **kwargs)
finally:
TRACE_STACK.pop()
return w
Empty file added tests/hacking/__init__.py
Empty file.
Loading

0 comments on commit 04b8651

Please sign in to comment.