コード例 #1
1
ファイル: colors.py プロジェクト: 249550148/pycallgraph
def main():
    graphviz = GraphvizOutput()
    pycallgraph = PyCallGraph(
        output=graphviz,
        config=Config(include_stdlib=True)
    )

    pycallgraph.start()
    import HTMLParser  # noqa
    pycallgraph.stop()

    # Set the edge colour to black for all examples
    graphviz.edge_color_func = lambda e: Color(0, 0, 0)

    # Default node colouring
    graphviz.output_file = 'colours-default.png'
    graphviz.done()

    def run(func, output_file):
        graphviz.node_color_func = func
        graphviz.output_file = output_file
        graphviz.done()

    run(rainbow, 'colors-rainbow.png')
    run(greyscale, 'colors-greyscale.png')
    run(orange_green, 'colors-orange-green.png')
    run(rand, 'colors-random.png')
コード例 #2
0
    def process_view(self, request, callback, callback_args, callback_kwargs):

        if settings.DEBUG and 'graph' in request.GET:
            pycallgraph = PyCallGraph(output=GraphvizOutput(
                output_file='callgraph-' + str(time.time()) + '.png'))
            pycallgraph.start()
            self.pycallgraph = pycallgraph
コード例 #3
0
def create_graph(output_type='dot'):
    '''
    starts the graph call. Keep the returned object and run done() on it to finish the graph creation.
    '''

    config = Config()
    config.trace_filter = GlobbingFilter(exclude=[
        'pycallgraph.*',
        'django.core.*',
        'collections.*',
        'copy.*',
        'threading.*',
        'logging.*',
        'multiprocessing.*',
        'inspect.*',
        'string.*',
        'Cookie.*',
        'importlib.*',
        'pdb.*',
        'shutil.*',
        're.*',
        'os.*',
        'sys.*',
        'json.*',
        'decimal.*',
        'urllib.*',
    ])

    output_type = 'dot'
    output_file = 'tccallgraph-{}.{}'.format(str(time.time()), output_type)
    graphviz = GraphvizOutput(output_file=output_file, output_type=output_type)
    pycallgraph = PyCallGraph(output=graphviz, config=config)
    pycallgraph.start(reset=True)

    return pycallgraph
コード例 #4
0
ファイル: middleware.py プロジェクト: bkopanichuk/sev_sed_2
    def process_view(self, request, callback, callback_args, callback_kwargs):
        if settings.DEBUG and 'graph' in request.GET:
            visualize_modules = request.GET['graph'].split(',')
            exclude_extra = request.GET.get('exclude_extra', '').split(',')
            exclude = PyCallGraphMiddleware.DEFAULT_EXCLUDE + exclude_extra
            graph_output = request.GET.get('graph_output', 'png')
            groups = request.GET.get('groups', False)
            max_depth = int(request.GET.get('max_depth', 99999))
            tool = request.GET.get('tool', 'dot')
            ##https://graphviz.org/
            ## Roadmap

            if graph_output not in PyCallGraphMiddleware.VALID_OUTPUT_TYPE:
                raise Exception(
                    f'"{graph_output}" not in "{PyCallGraphMiddleware.VALID_OUTPUT_TYPE}"'
                )

            output_file = 'pycallgraph-{}-{}.{}'.format(
                time.time(), tool, graph_output)

            output = GraphvizOutput(output_file=output_file,
                                    tool=tool,
                                    output_type=graph_output)

            config = Config(groups=groups, max_depth=max_depth)
            config.trace_filter = GlobbingFilter(include=visualize_modules,
                                                 exclude=exclude)

            pycallgraph = PyCallGraph(output=output, config=config)
            pycallgraph.start()

            self.pycallgraph = pycallgraph
コード例 #5
0
    def __call__(self, request):

        # Code to be executed for each request before
        # the view (and later middleware) are called.
        if settings.DEBUG and self.to_debug(request):
            config = Config()
            config.trace_filter = GlobbingFilter(include=['contracts.*'],
                                                 exclude=[])
            graphviz = GraphvizOutput(output_file='callgraph-' +
                                      str(time.time()) + '.svg',
                                      output_type='svg')  # or 'png'
            pycallgraph = PyCallGraph(output=graphviz, config=config)
            pycallgraph.start()
            # noinspection PyAttributeOutsideInit
            self.pycallgraph = pycallgraph

            response = self.get_response(request)
            # Code to be executed for each request/response after
            # the view is called.

            self.pycallgraph.done()
        else:
            response = self.get_response(request)

        return response
コード例 #6
0
 def __enter__(self):
     self._provider = PyCallGraph(output=GraphvizOutput(
         output_file=path.join(
             self._path,
             f"{self._caller_name}.{self._configuration.format}"),
         output_format=self._configuration.format),
                                  config=self._config)
     return self
コード例 #7
0
ファイル: stat.py プロジェクト: mgroth0/mlib
def enable_py_call_graph(output):
    # Makes code about 4 times slower
    DEFAULT_PY_CALL_GRAPH = PyCallGraph(
        output=GraphvizOutput(
            output_file=mlib.file.abspath
        ),
        config=Config(
            max_depth=2
        )
    )
    atexit.register(DEFAULT_PY_CALL_GRAPH.done)
    DEFAULT_PY_CALL_GRAPH.start()
コード例 #8
0
class PyCallgraphProvider(CallgraphProviderBase):
    def __init__(self,
                 configuration: CallgraphConfiguration,
                 caller_name: str = None):
        super().__init__(configuration, caller_name)
        self._config = Config()
        self._config.trace_filter = GlobbingFilter(exclude=[
            'pycallgraph.*'
            'excallgraph', 'excallgraph.*', 'providers.*'
        ])
        if self._configuration.excludes is not None:
            self._config.trace_filter.exclude += self._configuration.excludes
        if self._configuration.includes is not None:
            self._config.trace_filter.include = self._configuration.includes

    def __enter__(self):
        self._provider = PyCallGraph(output=GraphvizOutput(
            output_file=path.join(
                self._path,
                f"{self._caller_name}.{self._configuration.format}"),
            output_format=self._configuration.format),
                                     config=self._config)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self._provider is not None:
            self._provider.stop()
            return self._provider.__exit__(exc_type, exc_val, exc_tb)

    def start(self):
        '''Starts Capturing Trace'''
        return self._provider.start()

    def stop(self):
        '''Stop Capture Trace'''
        return self._provider.stop()

    def get_path(self):
        return self._configuration.path

    def get_format(self):
        return self._configuration.format

    def create_path_if_not_exists(self):
        try:
            makedirs(self.get_path())
        except OSError as ex:
            if ex.errno == errno.EEXIST and os.path.isdir(self.get_path()):
                pass
            else:
                raise
コード例 #9
0
    def on_request(self, request_handler, run):
        filename = "%s/%s/pycallgraph.dot" % (self.output_path, run.id)

        config = Config()
        config.trace_filter = GlobbingFilter(include=[
            'element.*',
            'ioc.*',
        ])

        callgraph = PyCallGraph(output=DotGraphvizOutput(output_file=filename), config=config)
        callgraph.start()

        request_handler.run.add_data('callgraph', callgraph)
        request_handler.run.add_metric('callgraph', True)
コード例 #10
0
ファイル: protocol_test.py プロジェクト: chewi/xpra
 def profiling_context(self, basename):
     from pycallgraph import PyCallGraph, Config  #@UnresolvedImport
     from pycallgraph.output import GraphvizOutput  #@UnresolvedImport
     config = Config()
     graphviz = GraphvizOutput(output_file='%s-%i.png' %
                               (basename, time.monotonic()))
     return PyCallGraph(output=graphviz, config=config)
コード例 #11
0
def main():
    config = Config()
    # 关系图中包括(include)哪些函数名。
    #如果是某一类的函数,例如类gobang,则可以直接写'gobang.*',表示以gobang.开头的所有函数。(利用正则表达式)。
    config.trace_filter = GlobbingFilter(include=[
        'main',
        'pycallgraph.*',
        '*.secret_function',
    ])
    graphviz = GraphvizOutput()
    graphviz.output_file = 'basic.png'  #图片名称

    with PyCallGraph(output=graphviz):
        # coco
        modelpath = "model/"
        start = time.time()
        pose_model = general_coco_model(modelpath)  # 1.加载模型
        print("[INFO]Pose Model loads time: ", time.time() - start)
        # yolo
        start = time.time()
        _yolo = YOLO()  # 1.加载模型
        print("[INFO]yolo Model loads time: ", time.time() - start)

        img_path = 'D:/myworkspace/dataset/My_test/img/a_img/airplane_30.jpg'

        getImgInfo(img_path, pose_model, _yolo)
コード例 #12
0
    def wrapper(*args, **kwargs):
        # 隐藏其他多余函数信息
        config = Config()
        config.trace_filter = GlobbingFilter(exclude=[
            '_*',
            '*SourceFileLoader*',
            '*cache_from_source*',
            '*ModuleSpec*',
            '*spec_from_file_location*',
            '*path_hook_for_FileFinder*',
            'cb',
            '*FileFinder*',
            'pydev*',
            '*VFModule*',
            '__new__',
            '*spec',
            '*<*',
            '*>*',
            'pycallgraph.*',
            '*.secret_function',
        ])

        graphviz = GraphvizOutput()
        graphviz.output_file = '../graphs/{func}.png'.format(
            func=func.__name__)
        with PyCallGraph(output=graphviz, config=config):
            result = func(*args, **kwargs)
        return result
コード例 #13
0
    def test_run_with_trace(self):
        def rainbow(node):
            return Color.hsv(node.time.fraction * 0.8, 0.4, 0.9)

        def greyscale(node):
            return Color.hsv(0, 0, node.time.fraction / 2 + 0.4)

        def orange_green(node):
            return Color( 0.2 + node.time.fraction * 0.8,
                          0.2 + node.calls.fraction * 0.4 ,
                          0.2)

        from pycallgraph.output import GraphvizOutput
        from pycallgraph import PyCallGraph

        graphviz = GraphvizOutput()
        graphviz.output_file = 'basic.png'
        graphviz.edge_color_func = lambda e: Color(0, 0, 0)
        #graphviz.node_color_func = rainbow #orange_green # greyscale

        config = Config(include_stdlib=True)#max_depth=10)
        config.trace_filter = GlobbingFilter(include=['osbot*','pbx*','boto3*'])

        with PyCallGraph(output=graphviz, config=config):
            try:
                self.handler.run(Test_Data.api_gw_payload_help)
            except Exception as error:
                Dev.pprint(error)
コード例 #14
0
def generate_call_graph(args):
    """Performance debug function, will be (re)moved later. """
    assert args.model_shape_file, '--model_texture_file needs to be provided to save the pca model'
    assert args.model_texture_file, '--model_texture_file needs to be provided to save the pca model'
    assert args.shape_type, '--shape_type the type of dataset, see datasets module'

    dataset_module = import_dataset_module(args.shape_type)

    from pycallgraph import PyCallGraph
    from pycallgraph.output import GraphvizOutput

    graphviz = GraphvizOutput(output_file='filter_none.png')

    with PyCallGraph(output=graphviz):
        shape_model = pca.PCAModel(args.model_shape_file)
        texture_model = pca.PCAModel(args.model_texture_file)

        input_points = dataset_module.IMMPoints(filename='/data/imm_face_db/40-3m.asf')
        input_image = input_points.get_image()

        mean_points = dataset_module.IMMPoints(points_list=shape_model.mean_values)
        mean_points.get_scaled_points(input_image.shape)

        reconstruction.reconstruct_texture(
            input_image,  # src image
            input_image,  # dst image
            texture_model,
            input_points,  # shape points input
            mean_points,   # shape points mean
        )
コード例 #15
0
def make_callgraph(name: str,
                   id: str,
                   dry_run=NO_CALL_GRAPHS) -> 'PyCallGraph':
    """
    :param name: file name used to generate the call graph
    :param id:  if of the image
    :param dry_run: if True do not generate a call graph
    :return: a context manager
    """
    class DummyCtx:
        def __enter__(self):
            pass

        def __exit__(self, exc_type, exc_val, exc_tb):
            pass

    if dry_run:
        return DummyCtx()

    config = Config()
    config.trace_filter = GlobbingFilter(exclude=[
        'pycallgraph.*', 'tornado*', '*SynchronizedStatStreamStruct*'
    ])
    output = GraphvizOutput(
        output_file='call_graphs/{}_{}.png'.format(name, id))
    return PyCallGraph(output=output, config=config)
コード例 #16
0
def main():
    if sys.version_info[0] < 3:
        raise Exception("Moosezmachine requires Python 3.")

    parser = argparse.ArgumentParser()
    parser.add_argument('--file')
    parser.add_argument('--profile')
    parser.add_argument('--breakpoint')
    parser.add_argument('--transcript')
    parser.add_argument('--breakattext')
    data = parser.parse_args()
    filename = data.file
    breakpoint = data.breakpoint
    profile = data.profile
    breakattext = data.breakattext
    transcript = data.transcript
    if breakpoint and not breakpoint.startswith('0x'):
        breakpoint = '0x' + breakpoint
    try:
        while True:
            try:
                if profile:
                    from pycallgraph import PyCallGraph
                    from pycallgraph.output import GraphvizOutput
                    with PyCallGraph(output=GraphvizOutput()):
                        start(filename, breakpoint, breakattext, transcript)
                else:
                    start(filename, breakpoint, breakattext, transcript)
            except ResetException:
                print("Resetting...")
                time.sleep(1)
    except QuitException:
        print("Thanks for playing!")
コード例 #17
0
def main():
    """The entry point of the program"""
    args = parse_cmdline_args()
    level = logging.WARNING
    if args.verbose:
        level = logging.INFO
    if args.debug:
        level = logging.DEBUG
    logging.basicConfig(format='%(filename)s:%(lineno)d %(message)s', level=level)

    if args.port < PORT_RANGE[0] or args.port > PORT_RANGE[1]:
        print "The port must be from {0} to {1}".format(PORT_RANGE[0], PORT_RANGE[1])
        exit(0)

    if(args.backend is not None):
        from backend import Worker
        if(args.backend != True):
            worker = Worker(args.backend, args.port)
        else:
            worker = Worker(None, args.port)
        if not args.profile:
            worker.start()
        else:
            from pycallgraph import PyCallGraph
            from pycallgraph.output import GraphvizOutput
            with PyCallGraph(output=GraphvizOutput()):
                worker.start()
    elif(args.interface is not False):
        import interface
        interface.start_interface(args.no_restore)
    elif(args.reload is not False):
        import os, signal
        with open('.pid', 'r') as file:
            pid = int(file.read())
        os.kill(pid, signal.SIGUSR1)
コード例 #18
0
def measure():
    graphviz = GraphvizOutput()
    graphviz.output_file = 'secAdapter3.png'
    with PyCallGraph(output=graphviz):

        modelData2DB(mergeData(createConArango('claimOmania')),
                     createConArango('claimOmania'))
コード例 #19
0
def havafun():
    from pycallgraph import PyCallGraph
    from pycallgraph.output import GraphvizOutput
    graphviz = GraphvizOutput()
    graphviz.output_file = 'basic.png'
    with PyCallGraph(output=graphviz):
        main_VerboseTime_log()
コード例 #20
0
ファイル: recursive.py プロジェクト: e-alizadeh/pycallgraph
def main():
    graphviz = GraphvizOutput()
    graphviz.output_file = "recursive.png"

    with PyCallGraph(output=graphviz):
        for a in range(1, 10):
            factorial(a)
コード例 #21
0
ファイル: profile.py プロジェクト: timokau/wsn-embedding-rl
def profile(rand=np.random):
    """Profile the embedding"""
    config = Config()
    config.trace_filter = GlobbingFilter(exclude=["pycallgraph.*"])
    graphviz = GraphvizOutput(output_file=f"pc.png")
    pcg = PyCallGraph(output=graphviz, config=config)
    main(rand, pcg)
コード例 #22
0
ファイル: large.py プロジェクト: zyxue/pycallgraph
def main():
    gephi = GephiOutput()
    gephi.output_file = 'large.gdf'

    with PyCallGraph(output=gephi):
        from urllib2 import urlopen
        from xml.dom.minidom import parseString
        parseString(urlopen('http://w3.org/').read())
コード例 #23
0
ファイル: regexp.py プロジェクト: ipentest/hacking
    def run(self, output, config):
        graphviz = GraphvizOutput()
        graphviz.output_file = output
        self.expression = r'^([^s]).*(.)\2.*\1$'

        with PyCallGraph(config=config, output=graphviz):
            self.precompiled()
            self.onthefly()
コード例 #24
0
        def fn_decorated(*args, **kwargs):
            """Crea la función decorada."""

            graphviz = GraphvizOutput()
            graphviz.output_file = profiling_result_path

            with PyCallGraph(output=graphviz, config=None):
                fn(*args, **kwargs)
コード例 #25
0
ファイル: large.py プロジェクト: zyxue/pycallgraph
def main():
    graphviz = GraphvizOutput()
    graphviz.output_file = 'large.png'
    config = Config(include_stdlib=True)

    with PyCallGraph(output=graphviz, config=config):
        from urllib2 import urlopen
        from xml.dom.minidom import parseString
        parseString(urlopen('http://w3.org/').read())
コード例 #26
0
def main():
    graphviz = GraphvizOutput()
    graphviz.output_file = 'basic.png'

    with PyCallGraph(output=graphviz):
        person = Person()
        for a in xrange(10):
            person.add_banana(Banana())
        person.eat_bananas()
コード例 #27
0
def main():
    gephi = GephiOutput()
    gephi.output_file = 'basic.gdf'

    with PyCallGraph(output=gephi):
        person = Person()
        for a in xrange(10):
            person.add_banana(Banana())
        person.eat_bananas()
コード例 #28
0
    def __call__(self, *args, **kwargs):
        from pycallgraph import PyCallGraph
        from pycallgraph.output import GraphvizOutput

        with PyCallGraph(output=GraphvizOutput(
                output_file='/tmp/pycallgraph.svg', output_type='svg')):
            return self.__object(*args, **kwargs)

        pass
コード例 #29
0
def create_graph(output_type='dot'):
    '''
    starts the graph call. Keep the returned object and run done() on it to finish the graph creation.
    '''

    config = Config()
    config.trace_filter = GlobbingFilter(exclude=['pycallgraph.*', 'django.core.*', 'collections.*', 'copy.*',
                                                  'threading.*', 'logging.*', 'multiprocessing.*', 'inspect.*',
                                                  'string.*', 'Cookie.*', 'importlib.*', 'pdb.*', 'shutil.*',
                                                  're.*', 'os.*', 'sys.*', 'json.*', 'decimal.*', 'urllib.*',
                                                  ])

    output_type = 'dot'
    output_file = 'tccallgraph-{}.{}'.format(str(time.time()), output_type)
    graphviz = GraphvizOutput(output_file=output_file, output_type=output_type)
    pycallgraph = PyCallGraph(output=graphviz, config=config)
    pycallgraph.start(reset=True)

    return pycallgraph
コード例 #30
0
 def callwrapper(*args, **kwargs):
     if callwrapper.already_called or not enabled:
         return func(*args, **kwargs)
     callwrapper.already_called = True
     graphviz = GraphvizOutput()
     graphviz.output_file = config.profileVisualizationsPath + (
         '%s.png' % str(func.__name__))
     with PyCallGraph(output=graphviz):
         result = func(*args, **kwargs)
     return result
コード例 #31
0
def profile(data):
    from pycallgraph import PyCallGraph
    from pycallgraph.output import GraphvizOutput
    data = data
    graphviz = GraphvizOutput(
        output_file=
        'C:/Users/Rajiv Sarvepalli/Projects/Data for GMU/tests/profile_STATS.png'
    )
    with PyCallGraph(output=graphviz):
        matrix_stats(data)
コード例 #32
0
    def handle(self):
        if conf.MEASUREMENT_MODE_PROCESSOR:

            utilities.clean_folder(conf.PROF_FOLDER)

            if conf.PROFILER == 'cProfiler':
                import cProfile
                import pstats
                pr = cProfile.Profile()
                pr.enable()
                self.handle_clean()
                pr.disable()

                #pr.dump_stats(conf.PROF_FILE_PROCESSOR + "pickle") #pickled

                #readable
                sortby = 'cumulative'
                ps = pstats.Stats(pr,
                                  stream=open(
                                      conf.PROF_FILE_PROCESSOR + "prof",
                                      'w')).sort_stats(sortby)
                ps.print_stats()

            elif conf.PROFILER == 'LineProfiler':
                import line_profiler
                import pstats
                import io
                pr = line_profiler.LineProfiler(
                    self.handle_clean, get_sketches_from_relays_non_blocking,
                    Classes.CountSketchCt.aggregate, op.median_operation,
                    op.mean_operation, op.variance_operation)
                pr.enable()
                self.handle_clean()
                pr.disable()

                pr.print_stats(open(conf.PROF_FILE_PROCESSOR + "prof",
                                    'w'))  #readable
                #pr.dump_stats(conf.PROF_FILE_PROCESSOR + "pickle") #pickled

            elif conf.PROFILER == "viz":
                from pycallgraph import PyCallGraph
                from pycallgraph.output import GraphvizOutput
                from pycallgraph import Config

                config = Config(max_depth=conf.DEPTH)
                graphviz = GraphvizOutput()
                graphviz.output_file = conf.PROF_FILE_PROCESSOR + 'png'
                with PyCallGraph(output=graphviz, config=config):
                    self.handle_clean()

            else:
                self.handle_clean()

        else:
            self.handle_clean()
コード例 #33
0
def main():
    graphviz = GraphvizOutput()
    graphviz.output_file = "large.png"
    config = Config(include_stdlib=True)

    with PyCallGraph(output=graphviz, config=config):
        from xml.dom.minidom import parseString

        import requests

        parseString(requests.get("https://w3.org/").content)