Beispiel #1
1
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')
Beispiel #2
0
def main():
    graphviz = GraphvizOutput()
    graphviz.output_file = "recursive.png"

    with PyCallGraph(output=graphviz):
        for a in range(1, 10):
            factorial(a)
    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)
Beispiel #4
0
def measure():
    graphviz = GraphvizOutput()
    graphviz.output_file = 'secAdapter3.png'
    with PyCallGraph(output=graphviz):

        modelData2DB(mergeData(createConArango('claimOmania')),
                     createConArango('claimOmania'))
Beispiel #5
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()
Beispiel #6
0
def main():
    graphviz = GraphvizOutput()
    graphviz.output_file = 'recursive.png'

    with PyCallGraph(output=graphviz):
        for a in xrange(1, 10):
            factorial(a)
Beispiel #7
0
def graphiz_setup(tool='dot'):
    graphviz = GraphvizOutput()
    graphviz.output_file = os.path.join(
        LocalConfig.ROOT, 'charts', 'images',
        'basic-{}-{}-v{}.png'.format(LocalConfig.ITERATIONS, tool, version))
    graphviz.tool = tool
    return graphviz
    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
Beispiel #9
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)
        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)
Beispiel #11
0
    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()
Beispiel #12
0
def main():
    graphviz = GraphvizOutput()
    graphviz.output_file = 'regexp.png'
    config = Config(include_stdlib=True)

    with PyCallGraph(output=graphviz, config=config):
        reo = compile()
        match(reo)
Beispiel #13
0
    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()
Beispiel #14
0
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())
Beispiel #15
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()
Beispiel #16
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()
Beispiel #17
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()
Beispiel #18
0
def main():
    """The entry point of the program"""

    if len(sys.argv) == 1:
        argparser.print_help()

    if "-b" in sys.argv and (sys.argv.index("-b") + 1 < len(sys.argv)):
        config_file = sys.argv[sys.argv.index("-b") + 1]
        imp.load_source("__config_file", config_file)

    args = argparser.parse_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:
        if args.influxdb is not None:
            from ipc import influx

            influx.init(args.influxdb)
        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
            import ipc.mpi
            import os

            graphviz = GraphvizOutput()
            graphviz.output_file = "pycallgraph_%d.png" % (ipc.mpi.rank)
            with PyCallGraph(output=graphviz):
                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)
Beispiel #19
0
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())
Beispiel #20
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
Beispiel #21
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()
    def run(self, output, config):
        graphviz = GraphvizOutput()
        graphviz.output_file = output
        self.expression = r'^([^s]).*(.)\2.*\1$'

        with PyCallGraph(config=config, output=graphviz):
            # 执行  api
            run()
            run2()
            for _ in range(10):
                foo()
Beispiel #23
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)
Beispiel #24
0
    def __init__(self, **kwargs):
        """
        Create and initialize the Graph object.

        # Arguments
            kwargs (dict): change any attributes or initialize new attributes with
                           this dictionary

        """
        self.graph_attributes = None
        GraphvizOutput.__init__(self, **kwargs)
Beispiel #25
0
def main():
    graphviz = GraphvizOutput()
    graphviz.output_file = 'basic.png'
    config = Config()
    config.max_depth = 5  # 控制最大追踪深度

    with PyCallGraph(output=graphviz, config=config):
        person = Person()
        for a in range(10):
            person.add_banana(Banana())
        person.eat_bananas()
    def run(self, output, config):
        graphviz = GraphvizOutput()
        graphviz.output_file = output
        self.expression = r'^([^s]).*(.)\2.*\1$'

        with PyCallGraph(config=config, output=graphviz):
            # 执行  api
            run()
            run2()
            for _ in range(10):
                foo()
Beispiel #27
0
    def callgraphwrapper(*args, **kwargs):
        if flag == 1 and ISCALLGRAPH:
            config = Config()
            config.trace_filter = GlobbingFilter(exclude=['thirdparty.*'])
            graphviz = GraphvizOutput()
            graphviz.output_file = 'docx/callGraph.png'

            with PyCallGraph(output=graphviz, config=config):
                result = func(*args, **kwargs)
        else:
            result = func(*args, **kwargs)
        return result
Beispiel #28
0
    def generate_callgraph(*args, **kwargs):
        """ set up before starting generate callgraph and take function func as starting point """
        from pycallgraph import PyCallGraph
        from pycallgraph import Config
        from pycallgraph.output import GraphvizOutput

        graphviz = GraphvizOutput()
        graphviz.output_file = 'colorvim.png'
        config = Config(groups=True)

        with PyCallGraph(config=config, output=graphviz):
            func(*args, **kwargs)
Beispiel #29
0
def single_analysis(config, name):
    """Perform profiling analysis for each test case, separately."""
    # graphviz = GephiOutput()
    graphviz = GraphvizOutput()
    graphviz.output_file = name

    print "Preparing test case..."
    radio, lines = _prepare_test_case()

    print "Running test case..."
    with PyCallGraph(output=graphviz, config=config):
        _run_test_case(radio, lines)
Beispiel #30
0
	def run(self):
		try:
			if self.profiling:
				self.logger.warn("PROFILING MODE, EXTRACTED DATA WILL NOT BE SAVED.")
				graphviz = GraphvizOutput()
				graphviz.output_file = "logs/"+self.name+'_profile.png'
				with PyCallGraph(output=graphviz):
					self.onAnalyzeVid()
			else:
				self.onAnalyzeVid()
				self.writeToDB(force=True)
		except Exception as e:
			self.logger.error(e)
Beispiel #31
0
 def inner(*args, **kwds):
     try:
         graphviz = GraphvizOutput()
         graphviz.output_file = "{fold}_{count}.{type}".format(
             fold=os.path.join(self.output_folder, func.__name__),
             count=self.graph_count,
             type=self.output_type)
         graphviz.output_type = self.output_type
         self.graph_count += 1
         with PyCallGraph(output=graphviz):
             return func(*args, **kwds)
     except:
         return func(*args, **kwds)
Beispiel #32
0
def main():
    import_list = (
        'pickle',
        'htmllib',
        'urllib2',
    )
    graphviz = GraphvizOutput()
    config = Config(include_stdlib=True)

    for module in import_list:
        graphviz.output_file = 'import-{}.png'.format(module)
        with PyCallGraph(output=graphviz, config=config):
            __import__(module)
def main():
    """The entry point of the program"""

    if(len(sys.argv) == 1):
        argparser.print_help()

    if "-b" in sys.argv and (sys.argv.index("-b")+1 < len(sys.argv)):
        config_file = sys.argv[sys.argv.index("-b")+1]
        imp.load_source('__config_file', config_file)
        
    args = argparser.parse_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):
        if (args.influxdb is not None):
            from ipc import influx
            influx.init(args.influxdb)
        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
            import ipc.mpi
            import os
            graphviz = GraphvizOutput()
            graphviz.output_file = 'pycallgraph_%d.png' % (ipc.mpi.rank)
            with PyCallGraph(output=graphviz):
                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)
Beispiel #34
0
def main():
    import_list = (
        "pickle",
        "html.parser",
        "requests",
        # TODO: import-requests.png is not generated as the other two libraries.
    )
    graphviz = GraphvizOutput()
    config = Config(include_stdlib=True)

    for module in import_list:
        graphviz.output_file = f"import-{module}.png"
        with PyCallGraph(output=graphviz, config=config):
            __import__(module)
Beispiel #35
0
def run(name, trace_filter=None, config=None, comment=None):
    if not config:
        config = Config()

    if trace_filter:
        config.trace_filter = trace_filter

    graphviz = GraphvizOutput()
    graphviz.output_file = "filter-{}.png".format(name)
    if comment:
        graphviz.graph_attributes["graph"]["label"] = comment

    with PyCallGraph(config=config, output=graphviz):
        banana = Banana()
        banana.eat()
Beispiel #36
0
def run(name, trace_filter=None, config=None, comment=None):
    if not config:
        config = Config()

    if trace_filter:
        config.trace_filter = trace_filter

    graphviz = GraphvizOutput()
    graphviz.output_file = 'filter-{}.png'.format(name)
    if comment:
        graphviz.graph_attributes['graph']['label'] = comment

    with PyCallGraph(config=config, output=graphviz):
        banana = Banana()
        banana.eat()
Beispiel #37
0
def test_files(fns, quiet=False, profile=False):
    for fn in fns:
        try:
            elf = ELFFile(open(fn))
        except ELFError:
            if not quiet:
                print "Skipping non-ELF file:", fn
            continue

        if not elf.has_dwarf_info():
            if not quiet:
                print "No dwarf info for {}.".format(fn)
            continue

        dwarfinfo = elf.get_dwarf_info()
        dwarf_functions = get_functions(dwarfinfo)

        engine_functions = {}
        for engine in ENGINES:
            this_engine = Static(fn, debug=0,
                                 static_engine=engine)  #no debug output
            if args.profile:
                #needs pycallgraph
                from pycallgraph import PyCallGraph
                from pycallgraph.output import GraphvizOutput
                graphviz = GraphvizOutput()
                graphviz.output_file = 'prof.png'
                with PyCallGraph(output=graphviz):
                    this_engine.process()
            else:
                this_engine.process()
            engine_functions[engine] = {
                x.start
                for x in this_engine['functions']
            }

        for engine, functions in engine_functions.iteritems():
            missed = dwarf_functions - functions
            total_fxns = len(dwarf_functions)
            short_fn = fn.split("/")[-1] if "/" in fn else fn
            if len(missed) == 0:
                print "{} {}: {} found all {} function(s).".format(
                    ok_green, short_fn, engine, total_fxns)
            else:
                fmt = "{} {}: {} missed {}/{} functions: {}."
                print fmt.format(warn, short_fn, engine, len(missed),
                                 total_fxns,
                                 ", ".join(hex(fxn) for fxn in missed))
Beispiel #38
0
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)
Beispiel #39
0
def group_analysis(ini, end, config=None):
    """Perform one profiling analysis for all the test cases, together.
    Args:
        ini (int): First test case number analyzed.
        end (int): Last test case number analyzed.
        config (Config): Configuration object for PyCallGraph.
    """

    # graphviz = GephiOutput()
    graphviz = GraphvizOutput()
    graphviz.output_file = _generate_name_output(ini, end)

    with PyCallGraph(output=graphviz, config=config):
        for num in range(ini, end + 1):
            print("Running test case number", num, "in a group analysis.")
            _run_test_case(num)
Beispiel #40
0
 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)
Beispiel #41
0
def main_with_callgraph(paramFilename):

    from pycallgraph import PyCallGraph
    from pycallgraph import Config
    from pycallgraph import GlobbingFilter
    from pycallgraph.output import GraphvizOutput

    config = Config()
    config.trace_filter = GlobbingFilter(exclude=[
        'vtk.*',
        'evtk.*',
        'imageToVTK',
    ])
    graphviz = GraphvizOutput()
    graphviz.output_file = 'euler2d_callgraph.png'

    with PyCallGraph(output=graphviz, config=config):
        main()
Beispiel #42
0
def test_files(fns,quiet=False,profile=False):
  for fn in fns:
    try:
      elf = ELFFile(open(fn))
    except ELFError:
      if not quiet:
        print "Skipping non-ELF file:",fn
      continue

    if not elf.has_dwarf_info():
      if not quiet:
        print "No dwarf info for {}.".format(fn)
      continue

    dwarfinfo = elf.get_dwarf_info()
    dwarf_functions = get_functions(dwarfinfo)

    engine_functions = {}
    for engine in ENGINES:
      this_engine = Static(fn, debug=0, static_engine=engine) #no debug output
      if args.profile:
        #needs pycallgraph
        from pycallgraph import PyCallGraph
        from pycallgraph.output import GraphvizOutput
        graphviz = GraphvizOutput()
        graphviz.output_file = 'prof.png'
        with PyCallGraph(output=graphviz):
          this_engine.process()
      else:
        this_engine.process()
      engine_functions[engine] = {x.start for x in this_engine['functions']}

    for engine,functions in engine_functions.iteritems():
      missed = dwarf_functions - functions
      total_fxns = len(dwarf_functions)
      short_fn = fn.split("/")[-1] if "/" in fn else fn
      if len(missed) == 0:
        print "{} {}: {} found all {} function(s).".format(ok_green, short_fn, engine, total_fxns)
      else:
        fmt = "{} {}: {} missed {}/{} functions: {}."
        print fmt.format(warn, short_fn, engine,
                len(missed), total_fxns, ", ".join(hex(fxn) for fxn in missed))
Beispiel #43
0
def gscontext(filename, exclude=None, max_depth=None):
    """Generate a call graph for the enclosed context

    Output a call graph to the chosen filename (introspecting the
    format along the way), optionally excluding some items.

    Args:
        filename (str): The output filename
	exclude (Optional[list]): The globbing strings to exclude. Defaults to ['graphstack.*'].
	max_depth (Optional[int]): The maximum recursion depth to plot. Defaults to infinite.

    """

    globkwargs = {
        'exclude': [
            'graphstack.*',
        ],
    }
    if exclude is not None:
    	globkwargs['exclude'].extend(exclude)
    if max_depth is not None:
        globkwargs['max_depth'] = max_depth

    # Configure exclusion filtering
    config = Config()
    config.trace_filter = GlobbingFilter(**globkwargs)

    # Configure GraphViz output
    fnsplit = os.path.splitext(filename)
    if len(fnsplit) == 1:
        outfile = filename + '.pdf'
        filetype = 'pdf'
    elif len(fnsplit) == 2:
        outfile = filename
        filetype = fnsplit[1][1:]
    graphviz = GraphvizOutput(output_file=outfile)
    graphviz.output_type = filetype

    # Set up context manager
    with PyCallGraph(output=graphviz, config=config):
        yield
Beispiel #44
0
def test_files(fns,quiet=False,profile=False,runtime=False):
  for fn in fns:
    short_fn = fn.split("/")[-1] if "/" in fn else fn
    if os.path.isdir(fn):
      if not quiet:
        print("{} {}: skipping directory".format(notice, short_fn))
      continue
    try:
      elf = ELFFile(open(fn, "rb"))
    except ELFError:
      if not quiet:
        print("{} {}: skipping non-ELF file".format(notice, short_fn))
      continue

    arch = elf['e_machine']
    if arch not in SUPPORTED:
      if not quiet:
        print("{} {}: skipping ELF with unsupported architecture `{}`".format(notice, short_fn, arch))
      continue

    engine_functions = {}
    engine = "builtin"
    try:
      this_engine = Static(fn, debug=0) #no debug output
      if args.profile:
        #needs pycallgraph
        from pycallgraph import PyCallGraph
        from pycallgraph.output import GraphvizOutput
        graphviz = GraphvizOutput()
        graphviz.output_file = 'prof.png'
        with PyCallGraph(output=graphviz):
          this_engine.process()
      else:
        this_engine.process()
      engine_functions[engine] = {x.start for x in this_engine['functions']}
    except KeyboardInterrupt:
      print("{} User stopped processing test cases.".format(notice))
      sys.exit()
    except MemoryError:
      #print("{} {}: bap encountered a memory error.".format(fail, short_fn, engine)
      continue
    except Exception as e:
      print("{} {}: {} engine failed to process file with `{}'".format(fail, short_fn, engine, e))
      continue
    if runtime:
      if not quiet:
        print("{} {}: {} ran without exceptions".format(ok_green, short_fn, engine))
      continue

    if runtime:
      continue

    if elf.has_dwarf_info():
      dwarfinfo = elf.get_dwarf_info()
      dwarf_functions = get_functions(dwarfinfo)
      for engine,functions in engine_functions.items():
        missed = dwarf_functions - functions
        total_fxns = len(dwarf_functions)
        if len(missed) == 0:
          print("{} {}: {} engine found all {} function(s)".format(ok_green,
                                                                   short_fn,
                                                                   engine,
                                                                   total_fxns))
        else:
          status = fail if len(missed) == total_fxns else warn
          if args.verbose:
            fmt = "{} {}: {} engine missed {}/{} function(s): {}"
            missed_s = ", ".join(hex(fxn) for fxn in missed)
            print(fmt.format(status, short_fn, engine,
                    len(missed), total_fxns, missed_s))
          else:
            fmt = "{} {}: {} engine missed {}/{} function(s)"
            print(fmt.format(status, short_fn, engine,
                    len(missed), total_fxns))
    else:
      for engine,functions in engine_functions.items():
        status = fail if len(functions) == 0 else ok_blue
        print("{} {}: {} engine found {} function(s). (dwarf info unavailable)".format(status, short_fn, engine, len(functions)))
Beispiel #45
0
from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput
from biots import biots


graphviz = GraphvizOutput()
graphviz.output_file = 'E:/pygraph/test.png'

with PyCallGraph(output=graphviz):
    biots.main()
    
    
    
Beispiel #46
0
    'wsgi.multiprocess': False,
    'wsgi.multithread': False,
    'wsgi.run_once': False,
    'wsgi.url_scheme': 'http',
    'wsgi.version': (1, 0),
}

def start_response(status, headers, exc_info=None):
    return None

frameworks = ['zunzuncito']

sys.path[0] = '.'
path = os.getcwd()

for framework in frameworks:
    os.chdir(os.path.join(path, framework))
    main = __import__('app', None, None, ['main']).main

    f = lambda: list(main(environ.copy(), start_response))
    st = profile.runctx('timeit(f, number=n)', globals(), {'n': 20})

    #profile.run('main(environ.copy(), start_response)')
#    profile.run('f()')

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

    with PyCallGraph(output=graphviz):
        main(environ.copy(), start_response)
Beispiel #47
0
    network.inferredFacts = closureDeltaGraph

    print("N0", network)

    hornrules = HornFromN3('https://raw.githubusercontent.com/RDFLib/FuXi/master/test/sameAsTestRules.n3')

    for rule in hornrules:
        network.buildNetworkFromClause(rule)

    print("N1", network)

    factGraph = Graph().parse(
        'https://raw.githubusercontent.com/RDFLib/FuXi/master/test/sameAsTestFacts.n3', format='n3')
    network.feedFactsToAdd(generateTokenSet(factGraph))
    print(closureDeltaGraph.serialize(format='n3'))

#import pycallgraph
#import sys
#pycallgraph.start()
#main()
#pycallgraph.make_dot_graph('example1.png')
#sys.exit(1)
from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput

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

with PyCallGraph(output=graphviz):
    main()
Beispiel #48
0
def graphiz_setup(tool='dot'):
    graphviz = GraphvizOutput()
    graphviz.output_file = os.path.join(LocalConfig.ROOT, 'charts', 'images',
                                        'basic-{}-{}-v{}.png'.format(LocalConfig.ITERATIONS, tool, version))
    graphviz.tool = tool
    return graphviz
Beispiel #49
0
 def __init__(self, source=None, saveflag=True, label="", **kwargs):
     self.source = source
     self.saveflag = saveflag
     self.label = label
     GraphvizOutput.__init__(self, **kwargs)
     self.graph_attributes['graph']['label'] = self.label
Beispiel #50
0
  # read the program file
  program_file = args.file
  program_raw = program_file.read()
  program_file.close()

  if PCG_AVAILABLE and args.pcg_graph:
    config = Config()
    config.trace_filter = GlobbingFilter(exclude=[
      'pedroclient.*',
      'Queue.*',
      'threading.*',
      'socket.*',
      'pycallgraph.*'
    ])

    parsing_graph_output = GraphvizOutput()
    parsing_graph_output.output_file = 'parsing_graph.png'

    tr_graph_output = GraphvizOutput()
    tr_graph_output.output_file = 'tr_graph.png'

  # parse the program's source code
  parsed_program = grammar.program.parseString(program_raw)

  if PCG_AVAILABLE and args.pcg_graph:
    with PyCallGraph(output=parsing_graph_output, config=config):
      program = dsl.program_from_ast(parsed_program)
  else:
    program = dsl.program_from_ast(parsed_program)

  # the name of the task to be called
Beispiel #51
0
config.trace_grouper = Grouper(groups=[
        "csv2df.reader.*" ,
        "csv2df.parser.*" ,
        "csv2df.emitter.*" ,
        "csv2df.validator.*" ,  # currently not used
        "csv2df.runner.*" ,

        'csv2df.util_row_splitter.*',
        'csv2df.specification.*',
    ])

config.trace_filter = GlobbingFilter
config.trace_filter = GlobbingFilter(exclude=[
        'csv2df.util_row_splitter.*',
        'csv2df.specification.*',
        "csv2df.reader.*" ,
        
        "config.*" , 


])

graphviz = GraphvizOutput()
graphviz.output_file = 'pcg_example_Vintage.svg'
graphviz.output_type = 'svg'

with PyCallGraph(output=graphviz, config=config):
#################### END PyCallGraph "decoration"
    vint = Vintage(year, month)