def wrapper(self, f, *args, **kwargs):
        # memory_profiler
        with StringIO() as s:
            rtn = profile(f, stream=s, precision=2)(*args, **kwargs)
            memory_value = self._memory_profiler_parse(s.getvalue())

        # line_profiler
        prof = LineProfiler()
        prof.add_function(f)

        rtn = prof.runcall(f, *args, **kwargs)
        with StringIO() as s:
            prof.print_stats(stream=s)
            mix, line_tmp = self._line_profiler_parse(s.getvalue())

        # memory line mix output
        template = self.L_M_TEMPLATE
        for l, m in zip(line_tmp, memory_value):
            l_m_mix = l[:5] + m
            mix.append(template.format(*l_m_mix))
        mix[self.L_M_HEADER_INDEX] = template.format(*self.L_M_HEADER)
        mix[self.L_M_SEPARATOR_INDEX] += "=" * 27
        self.logger.debug("line, memory profiler result\n" + "\n".join(mix))

        return rtn
Beispiel #2
0
 def newfunc(*args, **kwargs):
     if line_profile and getattr(sys, 'gettrace')() is None:
         from line_profiler import LineProfiler
         lp = LineProfiler()
         lp.timer_unit = 1e-6
         for f in profile_funcs:
             lp.add_function(f)
         lp_wrapper = lp(func)
         t = time.time()
         res = lp_wrapper(*args, **kwargs)
         t = time.time() - t
         if verbose:
             lp.print_stats()
         return res, [t]
     else:
         t_lst = []
         for i in range(100000):
             startTime = time.time()
             res = func(*args, **kwargs)
             t_lst.append(time.time() - startTime)
             if sum(t_lst) > min_time and len(t_lst) >= min_runs:
                 if hasattr(func, '__name__'):
                     fn = func.__name__
                 else:
                     fn = "Function"
                 if verbose:
                     print('%s: %f +/-%f (%d runs)' %
                           (fn, np.mean(t_lst), np.std(t_lst), i + 1))
                 return res, t_lst
Beispiel #3
0
    def test_staircase_stats_profile(self):
        """
        How to use line profiler in a script?
        https://stackoverflow.com/a/43377717/6610243

        Returns
        -------

        """
        return
        sequence = [0, 0, 1, 1, 1, 0, 0, 0, 1, 0]
        force_terminate = [0, 1, 0, 0, 0, 0, 1, 0, 0, 0]

        try:
            from line_profiler import LineProfiler
        except ImportError:
            return
        # Baseline: Total time: 2.07796 s s for N = 10000
        # Numpy: Total time: 2.11567 s
        # Combined 2 x n array: Total time: 1.5246 s
        # Total time: 1.19332 s
        # Remove creating temporary termination array for terminate == None: Total time: 1.19105 s
        # Switching 0 and 1 cases: Total time: 1.14139 s
        # Switching to: >2, 1, 0: Total time: 1.10141 s

        lp = LineProfiler()
        lp.add_function(strategy.DoubleStaircaseStrategy.get_staircase_stats)
        lp_wrapper = lp(lambda *args, **kwargs: [
            strategy.DoubleStaircaseStrategy.get_staircase_stats(
                *args, **kwargs) for _ in range(10000)
        ])
        lp_wrapper(sequence, step=(4, 2), force_terminate=force_terminate)
        with open("test_staircase_stats_profile.py", "w") as f:
            lp.print_stats(stream=f, output_unit=1e-3)
Beispiel #4
0
 def profiled_func(*args, **kwargs):
     profiler = LineProfiler()
     profiler.add_function(func)
     for f in follow:
         profiler.add_function(f)
     profiler.enable_by_count()
     return func(*args, **kwargs)
Beispiel #5
0
def line_profile(items):
    """A context manager which prints a line-by-line profile for the given functions, modules, or
    module names while execution is in its context.

    Example:

    with line_profile(__name__, Class.some_function, some_module):
        do_something()
    """
    from line_profiler import LineProfiler
    prof = LineProfiler()
    for item in items:
        if inspect.isfunction(item):
            prof.add_function(item)
        elif inspect.ismodule(item):
            prof.add_module(item)
        elif isinstance(item, str):
            prof.add_module(sys.modules[str])
        else:
            raise TypeError(
                'Inputs must be functions, modules, or module names')
    prof.enable()
    yield
    prof.disable()
    prof.print_stats()
Beispiel #6
0
def getNextDay():
    try:
        year = int(entryYear.get())
        month = int(entryMonth.get())
        day = int(entryDay.get())
    except ValueError as error:
        eLinter.set("时间格式不合法:")
    else:
        time_start = time.time()
        lp = LineProfiler()
        lp.add_function(main.isRunNian)
        lp_wrapper = lp(checkTime)
        lp_wrapper(year, month, day)
        lp.print_stats()
        str1 = checkTime(year, month, day)
        if '' != str1:
            eLinter.set(str1)
            eYear.set('')
            eMonth.set('')
            eDay.set('')
            eLunar.set('')
            return
        newYear, newMonth, newDay = main.getNextday(year, month, day)
        #在界面显示结果
        eYear.set(str(newYear))
        eMonth.set(str(newMonth))
        eDay.set(str(newDay))
        eLinter.set("")
        days = int(nextday.Lunar(newYear, newMonth, newDay).getDays())
        week = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
        #print(week[(days+1)%7])
        eLunar.set(
            nextday.test(newYear, newMonth, newDay) + " " +
            week[(days + 1) % 7])
Beispiel #7
0
 def benchmark(cls, func, *args):
     from line_profiler import LineProfiler
     prf = LineProfiler()
     prf.add_function(func)
     ret = prf.runcall(func, *args)
     prf.print_stats()
     return ret
Beispiel #8
0
        def jungleprofiler_wrapped_f(*args, **kwargs):
            ''' Wrapper that collects time and system usage data on wrapped function f'''

            # Set up LineProfiler
            lp = LineProfiler()
            lp.add_function(f)

            # Set up MemoryProfiler
            pass  # todo add Memory Profiler

            # Start Counters
            if self.t_prof: lp.enable_by_count()
            if self.m_prof: pass
            try:
                t0 = time.time()
                sio = io.StringIO()  # Collects redirected stdout
                with redirect_stdout(sio):
                    preturn = f(*args, **kwargs)
                self.stdout = sio.getvalue()
                t1 = time.time()
            finally:
                # Stop Counters
                if self.m_prof: lp.disable_by_count()
                if self.m_prof: pass  # todo add Memory Profiler

            # Collect Stats
            # print('Get Stats: %s' % lp.print_stats())

            self.walltime = t1 - t0
            return preturn, copy.deepcopy(self)
 def profiled_func(*args, **kwargs):
     try:
         profiler = LineProfiler()
         profiler.add_function(func)
         profiler.enable_by_count()
         return func(*args, **kwargs)
     finally:
         profiler.print_stats()
Beispiel #10
0
 def profiled_func(*args, **kwargs):
     try:
         profiler = LineProfiler()
         profiler.add_function(func)
         profiler.enable_by_count()
         return func(*args, **kwargs)
     finally:
         profiler.print_stats()
Beispiel #11
0
 def wrap(*args, **kwargs):
     profile = LineProfiler()
     profile.add_function(f)
     profile.enable_by_count()
     result = f(*args, **kwargs)
     profile.disable_by_count()
     profile.print_stats(sys.stdout)
     return result
Beispiel #12
0
 def DataReader_bin_test2(self):
     self.select_file(num=1)
     prf = LineProfiler()
     prf.add_function(self.read_bin_file_to_tx2)
     prf.runcall(self.read_bin_file_to_tx2, start=3 * 10**7, datapoints=10**6)
     prf.print_stats()
     print(len(self.x), math.log10((len(self.x))))
     self.plot_timecorse_of_move(show_it=1)
Beispiel #13
0
 def profiled_func(*args, **kwargs):
     try:
         lp = LineProfiler()
         lp.add_function(f)
         lp.enable_by_count()
         return f(*args, **kwargs)
     finally:
         lp.print_stats()
 def profiled_func(*args, **kwargs):
     line_profiler = LineProfiler()
     line_profiler.add_function(func)
     map(lambda x: line_profiler.add_function(x), self.follow)
     line_profiler.enable_by_count()
     result = func(*args, **kwargs)
     line_profiler.disable_by_count()
     line_profiler.print_stats(stripzeros=True)
     return result
 def decorator(*args, **kwargs):
     # line-profiler==3.0.2
     profiler = LineProfiler()
     try:
         profiler.add_function(func)
         profiler.enable_by_count()
         return func(*args, **kwargs)
     finally:
         profiler.dump_stats('/var/log/{}.lprof'.format(time.time()))
Beispiel #16
0
 def wrapper(*args, **kwargs):
     try:
         profiler = LineProfiler()
         profiler.add_function(func)
         for f in follow:
             profiler.add_function(f)
         profiler.enable_by_count()
         return func(*args, **kwargs)
     finally:
         profiler.print_stats()
Beispiel #17
0
 def DataReader_bin_test2(self):
     self.select_file(num=1)
     prf = LineProfiler()
     prf.add_function(self.read_bin_file_to_tx2)
     prf.runcall(self.read_bin_file_to_tx2,
                 start=3 * 10**7,
                 datapoints=10**6)
     prf.print_stats()
     print(len(self.x), math.log10((len(self.x))))
     self.plot_timecorse_of_move(show_it=1)
Beispiel #18
0
 def wrapped_fn(*args, **kwargs):
     try:
         profiler = LineProfiler()
         profiler.add_function(fn)
         for f in follow:
             profiler.add_function(f)
         profiler.enable_by_count()
         return fn(*args, **kwargs)
     finally:
         profiler.print_stats()
Beispiel #19
0
 def profiled_func(*args, **kwargs):
     try:
         profiler = LineProfiler()
         profiler.add_function(func)
         for f in follow:
             profiler.add_function(getattr(args[0], f))
         profiler.enable_by_count()
         return func(*args, **kwargs)
     finally:
         profiler.print_stats()
Beispiel #20
0
 def profiled_func(*args, **kwargs):
     try:
         pf = LineProfiler()
         pf.add_function(func)
         for f in follow:
             pf.add_function(f)
         pf.enable_by_count()
         return func(*args, **kwargs)
     finally:
         pf.print_stats()
Beispiel #21
0
def timetest(func, *para):
    p = LineProfiler()
    p.add_function(func)
    p.enable_by_count()

    p_wrapper = p(func)
    p_wrapper(*para)
    
    # Printing
    print(func(*para))
    p.print_stats()
Beispiel #22
0
    def wrapper(self, f, *args, **kwargs):
        prof = LineProfiler()
        prof.add_function(f)

        rtn = prof.runcall(f, *args, **kwargs)
        with StringIO() as f:
            prof.print_stats(stream=f)
            msg = "line_profiler result\n{}".format(f.getvalue())
            self.logger.debug(msg)

        return rtn
Beispiel #23
0
def profile_on(fcn_names=None):
    if fcn_names and HAS_LINE_PROFILER:
        pr = LineProfiler()
        for fcn_name in fcn_names:
            pr.add_function(fcn_name)
        pr.enable()
        return pr

    pr = cProfile.Profile()
    pr.enable()
    return pr
Beispiel #24
0
def profile_on(fcn_names=None):
    if fcn_names and HAS_LINE_PROFILER:
        pr = LineProfiler()
        for fcn_name in fcn_names:
            pr.add_function(fcn_name)
        pr.enable()
        return pr

    pr = cProfile.Profile()
    pr.enable()
    return pr
 def wrapper(*args, **kwargs):
     profiler = LineProfiler()
     profiler.add_function(fn)
     try:
         for f in follow:
             profiler.add_function(f)
         profiler.enable_by_count()
         return fn(*args, **kwargs)
     finally:
         profiler.print_stats(output_unit=1)
         profiler.dump_stats(report)
def run_profiling_by_line(func, kwargs):
    line_profiler = LineProfiler()
    functions = inspect.getmembers(inspect.getmodule(func), inspect.isfunction)
    function_instances = dict(functions).values()

    for function_instance in function_instances:
        if function_instance is not func:
            line_profiler.add_function(function_instance)

    line_profiler_wrapper = line_profiler(func)
    line_profiler_wrapper(**kwargs)
    line_profiler.print_stats()
Beispiel #27
0
 def profiled_func(*args, **kwargs):
     try:
         profiler = LineProfiler()
         profiler.add_function(func)
         for f in follow:
             if isinstance(f, basestring):
                 f = to_function(f)
             profiler.add_function(f)
         profiler.enable_by_count()
         return func(*args, **kwargs)
     finally:
         profiler.print_stats()
Beispiel #28
0
 def profiled_func(*args, **kwargs):
     try:
         profiler = LineProfiler()
         profiler.add_function(func)
         for f in follow:
             if isinstance(f, six.string_types):
                 f = to_function(f)
             profiler.add_function(f)
         profiler.enable_by_count()
         return func(*args, **kwargs)
     finally:
         profiler.print_stats()
Beispiel #29
0
 def profiled_func(*args, **kwargs):
     try:
         profiler = LineProfiler()
         profiler.add_function(func)
         if follow_all_methods:
             cls = args[0]  # class instance
             _add_all_class_methods(profiler, cls,
                                    except_=func.__name__)
         for f in follow:
             _add_function_or_classmethod(profiler, f, args)
         profiler.enable_by_count()
         return func(*args, **kwargs)
     finally:
         profiler.print_stats()
Beispiel #30
0
def create_line_profile(*args):
    line_profiler = LineProfiler()
    line_profiler.enable_by_count()

    for klass in args:
        for attr in dir(klass):
            func = getattr(klass, attr)
            condition = (not inspect.isfunction(func),
                         not inspect.ismethod(func))
            if all(condition):
                continue
            line_profiler.add_function(func)

    return line_profiler
Beispiel #31
0
    def __call__(self, *args, **kwargs):
        result = None
        if logger.getEffectiveLevel() == logging.MPROFILE:
            import sys
            result = self.function(*args, **kwargs)

            logger.debug(">>Tracing memory size : return object is %s bytes",
                         sys.getsizeof(result))

        elif logger.getEffectiveLevel() == logging.CPROFILE:
            import cProfile
            profile = cProfile.Profile()
            try:
                profile.enable()
                result = self.function(*args, **kwargs)
                profile.disable()
            finally:
                profile.print_stats()

        elif logger.getEffectiveLevel() == logging.LPROFILE:
            try:
                from line_profiler import LineProfiler
                try:
                    profiler = LineProfiler()
                    profiler.add_function(self.function)

                    profiler.enable_by_count()
                    result = self.function(*args, **kwargs)
                finally:
                    profiler.print_stats()
            except ImportError:
                logger.debug("Error importing line_profiler.")
                return self.function(*args, **kwargs)

        elif logger.getEffectiveLevel() == logging.MEMPROFILE:
            try:
                from memory_profiler import LineProfiler, show_results
                try:
                    profiler = LineProfiler()
                    profiler.add_function(self.function)
                    profiler.enable_by_count()
                    result = self.function(*args, **kwargs)
                finally:
                    show_results(profiler)
            except ImportError:
                logger.debug("Error importing memory_profiler.")
                result = self.function(*args, **kwargs)
        else:
            result = self.function(*args, **kwargs)
        return result
Beispiel #32
0
def process(cell_id):
    if strtobool(get_param(DbName.COMMON, 'profile')[0]):
        print('cell id : {}'.format(cell_id))
        pr = LineProfiler()
        rtg = RdfToGcnf(cell_id)
        pr.add_function(rtg.create_gcn_file)
        pr.enable()
        rtg.create_gcn_file()
        pr.disable()
        pr.print_stats()
        del rtg
    else:
        rtg = RdfToGcnf(cell_id)
        rtg.create_gcn_file()
        del rtg
Beispiel #33
0
def line(
        cls_runner: tp.Type[Perf],
        pattern_func: str,
        ) -> None:
    runner = cls_runner()
    for name in runner.iter_function_names(pattern_func):
        f = getattr(runner, name)
        profiler = LineProfiler()
        if not runner.meta:
            raise NotImplementedError('must define runner.meta')
        profiler.add_function(runner.meta[name].line_target)
        profiler.enable()
        f()
        profiler.disable()
        profiler.print_stats()
Beispiel #34
0
def speedtest_validate_transaction():
    # create a transaction
    b = bigchaindb.Bigchain()
    tx = b.create_transaction(b.me, b.me, None, 'CREATE')
    tx_signed = b.sign_transaction(tx, b.me_private)

    # setup the profiler
    profiler = LineProfiler()
    profiler.enable_by_count()
    profiler.add_function(bigchaindb.Bigchain.validate_transaction)

    # validate_transaction 1000 times
    for i in range(1000):
        b.validate_transaction(tx_signed)

    profiler.print_stats()
Beispiel #35
0
def _conduct_test_and_write_stats(cipher_obj: Cipher) -> bool:
    """
    The cipher object to run encryption and then decryption. Write to a file detailing the statistics of encryption
    and decryption.

    :param cipher_obj: (_cipher.Cipher) The cipher object to encrypt and decrypt with
    :return:           (bool)           THe success or failure of the encryption and decryption
    """

    # Setup for encrypting/decrypting with profiling
    lp = LineProfiler()  # Set up the line-profiler object
    module_name = str(type(cipher_obj)).split(".")[
        -2]  # Get the name of the module that cipher_obj uses
    class_name = str(type(cipher_obj)).split(".")[-1][
        0:-2]  # Get the class that cipher_obj is
    functions = eval("inspect.getmembers({}.{}, "
                     "predicate=inspect.isfunction)".format(
                         module_name, class_name))
    functions = [item[0] for item in functions
                 ][1:]  # Only want names. Also, ignore first element (init)
    functions.remove("encrypt_plaintext")
    functions.remove("decrypt_ciphertext")
    functions.remove("write_statistics")

    # Add all function/method to profile
    lp.add_function(undecorated.undecorated(cipher_obj.encrypt_plaintext))
    lp.add_function(undecorated.undecorated(cipher_obj.decrypt_ciphertext))
    for function in functions:
        exec("lp.add_function(undecorated.undecorated({}.{}.{}))".format(
            module_name, class_name, function))

    # Encrypt and decrypt. Also, profile TODO
    lp_wrapped = lp(cipher_obj.encrypt_plaintext)  # Wrap encrypt_plaintext()
    lp_wrapped()
    lp_wrapped = lp(cipher_obj.decrypt_ciphertext)  # Wrap decrypt_ciphertext()
    lp_wrapped()
    lp.print_stats()

    # Generate file name and write to that file containing the statistics of the encryption and decryption
    cipher_name = str(type(cipher_obj))
    cipher_name = cipher_name[cipher_name.rfind(".") + 1:-2]
    stats_file_path = "Resources/Files_Logs/{}__{}"\
                      .format(cipher_name, datetime.datetime.now().strftime("%Y-%m-%d_%Hh%Mm%Ss"))
    cipher_obj.write_statistics(stats_file_path)

    # Return the correctness of the encryption and decryption
    return cipher_obj.original_plaintext == cipher_obj.plaintext
Beispiel #36
0
def run_profiling(args):
    lprofiler = LineProfiler()

    monitor_fuctions = [
        api.problem.submit_key, api.problem.get_unlocked_pids,
        api.problem.get_solved_pids, api.problem.get_all_problems,
        api.problem.get_solved_problems, api.stats.get_score,
        api.cache.memoize, api.autogen.grade_problem_instance,
        api.autogen.get_problem_instance, api.autogen.get_number_of_instances
    ]

    for func in monitor_fuctions:
        lprofiler.add_function(func)

    lprofiler.enable()

    if args.stack:
        profiler = Profiler(use_signal=False)
        profiler.start()

    for func, a, kw in operations:
        func(*a, **kw)

    if args.stack:
        profiler.stop()

    lprofiler.disable()

    if args.print:
        print(profiler.output_text(unicode=True, color=True))
        lprofiler.print_stats()

    output = open(args.output, "w")

    if args.stack:
        output.write(profiler.output_text(unicode=True))

        if args.output_html is not None:
            output_html = open(args.output_html, "w")
            output_html.write(profiler.output_html())
            output_html.close()
            print("Wrote test info to " + args.output_html)

    lprofiler.print_stats(output)
    output.close()
    print("Wrote test info to " + args.output)
Beispiel #37
0
 def run_and_profile(self):
     if len(self._funcs_to_profile) > 0:
         profiler = LineProfiler()
         for func in self._funcs_to_profile:
             profiler.add_function(func)
         profiler.enable_by_count()
         try:
             yield
         finally:
             with io.StringIO() as str_stream:
                 profiler.print_stats(str_stream)
                 string = str_stream.getvalue()
             print(f'Writing profile data to "{self._output_filenmae}"')
             with open(self._output_filenmae, 'w') as fid:
                 fid.write(string)
     else:
         yield
Beispiel #38
0
def profile():
    import termcolor
    import time
    from line_profiler import LineProfiler

    epoch = int(time.time())
    outfile = f"compare50_profile_{epoch}.txt"
    profiler = LineProfiler()
    for f in PROFILE:
        profiler.add_function(f)
    profiler.enable_by_count()
    try:
        yield
    finally:
        with open(outfile, "w") as f:
            profiler.print_stats(stream=f)
        termcolor.cprint(f"Profiling data written to {outfile}", "yellow")
Beispiel #39
0
class Profiler(object):

    def __init__(self, *args):
        self.profile = LineProfiler()

        if len(args) > 0:
            for func in args:
                if callable(func):
                    self.add_function(func)

    def add_function(self, func):
        self.profile.add_function(func)

    def __enter__(self):
        self.profile.enable_by_count()

    def __exit__(self, type, value, traceback):
        self.profile.disable_by_count()
        self.profile.print_stats()
Beispiel #40
0
def run_profiling(args):
    lprofiler = LineProfiler() 

    monitor_fuctions = [api.problem.submit_key, api.problem.get_unlocked_pids, api.problem.get_solved_pids,
                        api.problem.get_all_problems, api.problem.get_solved_problems, api.stats.get_score,
                        api.cache.memoize, api.autogen.grade_problem_instance, api.autogen.get_problem_instance,
                        api.autogen.get_number_of_instances]

    for func in monitor_fuctions:
        lprofiler.add_function(func)

    lprofiler.enable()

    if args.stack:
        profiler = Profiler(use_signal=False)
        profiler.start()

    for func, a, kw in operations:
        func(*a, **kw)

    if args.stack:
        profiler.stop()

    lprofiler.disable()

    if args.print:
        print(profiler.output_text(unicode=True, color=True))
        lprofiler.print_stats()

    output = open(args.output, "w")

    if args.stack:
        output.write(profiler.output_text(unicode=True))

        if args.output_html is not None:
            output_html = open(args.output_html, "w")
            output_html.write(profiler.output_html())
            output_html.close()
            print("Wrote test info to " + args.output_html)

    lprofiler.print_stats(output)
    output.close()
    print("Wrote test info to " + args.output)
Beispiel #41
0
        ret = [name for name in availableAI]
    return GetResp((200, {"aiList": ret}))


@app.route('/')
@app.route('/index.html')
def Index():
    if request.url.startswith('https://'):
        url = request.url.replace('https://', "http://", 1)
        return redirect(url, 301)
    i = InfoDb.query.get(0)
    if i != None:
        aiOnly = i.ai_only
    else:
        aiOnly = False
    return render_template('index.html', aiOnly=aiOnly)


@app.route('/admin.html')
def Admin():
    if request.url.startswith('https://'):
        url = request.url.replace('https://', "http://", 1)
        return redirect(url, 301)
    return render_template('admin.html')


if pr:
    pr.add_function(GetGameInfo)
    pr.add_function(CellDb.Attack)
    pr.add_function(UpdateGame)
Beispiel #42
0
            m = DFMessage(fmt, elements, False)
        except ValueError:
            return self._parse_next()

        self._add_msg(m)

        return m


if __name__ == "__main__":
    import sys
    use_profiler = False
    if use_profiler:
        from line_profiler import LineProfiler
        profiler = LineProfiler()
        profiler.add_function(DFReader_binary._parse_next)
        profiler.add_function(DFReader_binary._add_msg)
        profiler.add_function(DFReader._set_time)
        profiler.enable_by_count()
                    
    filename = sys.argv[1]
    if filename.endswith('.log'):
        log = DFReader_text(filename)
    else:
        log = DFReader_binary(filename)
    while True:
        m = log.recv_msg()
        if m is None:
            break
        #print(m)
    if use_profiler:
Beispiel #43
0
    def _transform_STRIKED(self, match: Match) -> str:
        if not match['STRIKED_TEXT']: return ''
        return f"<s>{self._parse(match['STRIKED_TEXT'], 'STRIKED')}</s>"

    def _transform_SUPERSCRIPT(self, match: Match) -> str:
        if not match['SUPERSCRIPT_TEXT']: return ''
        return f"<sup>{self._parse(match['SUPERSCRIPT_TEXT'], 'SUPERSCRIPT')}</sup>"

    def _transform_SUBSCRIPT(self, match: Match) -> str:
        if not match['SUBSCRIPT_TEXT']: return ''
        return f"<sub>{self._parse(match['SUBSCRIPT_TEXT'], 'SUBSCRIPT')}</sub>"

    def _transform_HORIZ_RULE(self, match: Match) -> str:
        return f'<hr />'

    def _post_BACKSLASH_UNESCAPE(self, text: str) -> str:
        return self._backslash_escape_re.sub(r'\1', text)

d = DefaultRenderer()

if __name__ == '__main__':
    from line_profiler import LineProfiler

    lp = LineProfiler()
    lp.add_function(d._parse)
    lp.runcall(d.parse, '*****' * 2000)
    lp.print_stats()

print(d.parse('**__hi__**'))
# Test and profile TimeHistogram
#
# Copyright (C) 2010-2012 Huang Xin
# 
# See LICENSE.TXT that came with this file.
#import cProfile,pstats
from line_profiler import LineProfiler
import TimeHistogram

def run():
    psth = TimeHistogram.PSTHAverage('/home/chrox/dev/plexon_data/c04-stim-timing-8ms-rand-1.plx')
    psth.get_data()

if __name__ == '__main__':
    
    #cProfile.run('psth.get_data()','hist_profile')
    #p = pstats.Stats('hist_profile')
    #p.sort_stats('cumulative')
    #p.print_stats()
    
    profile = LineProfiler()
    profile.add_function(run)
    profile.add_function(TimeHistogram.PSTHAverage._process_unit)
    profile.run('run()')
    profile.print_stats()
    profile.dump_stats("hist_profile.lprof")
        for timestamp in bit_2_events[-5:]:
            print "unstrobed bit 2 t=%f" % timestamp
        print "found %d bit 3 events. Last 5 events are:" %(len(bit_3_events))
        for timestamp in bit_3_events[-5:]:
            print "unstrobed bit 3 t=%f" % timestamp
        
        unstrobed_word = pu.GetExtEvents(data, event='unstrobed_word', online=False)
        print "found %d unstrobed word events in which 10 events are:" %(len(unstrobed_word['value']))
        indices = np.arange(0,len(unstrobed_word['value']),len(unstrobed_word['value'])/10)
        for value,timestamp in zip(unstrobed_word['value'][indices],unstrobed_word['timestamp'][indices]) :
            binary_value = bin(value)
            print "unstrobed word:%s t=%f" % (binary_value,timestamp)

if __name__ == "__main__":
        #run()
        profile = LineProfiler()
        profile.add_function(run)
        profile.add_function(PlexUtil.GetExtEvents)
        profile.add_function(reconstruct_word)
        profile.run('run()')
        profile.print_stats()
        profile.dump_stats("testPlexFile_profile.lprof")
        
        #cProfile.run('run()','PlexFile_profile')
        #p = pstats.Stats('testPlexFile_profile.lprof')
        #p.sort_stats('cumulative')
        #p.print_stats()
        
        #print h.heap()

Beispiel #46
0
class SpecialTestRunner(SpecialTest):
    """
    Test runner, calls the specified test under specified profiler
    Mode = None - no profiler, "c" - cProfile, "l" - LineProfiler, "h" - hotshot
    """
    def __init__(self, test, mode=None):
        super(SpecialTestRunner, self).__init__()

        self.mode = mode
        self.test = test
        self.profiler = None

    def setup(self):
        if self.mode == 'c':
            import cProfile
            self.profiler = cProfile.Profile()

        elif self.mode == 'l':
            from line_profiler import LineProfiler
            self.profiler = LineProfiler()

        elif self.mode == 'h':
            import hotshot
            self.info['name'] = 'special.prof'
            self.profiler = hotshot.Profile(self.info['name'])

        self.test.setup()

    def run(self):
        if self.mode == 'c':
            self.profiler.enable()
        elif self.mode == 'l':
            self.profiler.enable_by_count()

            self.profiler.add_function(Handler.handle)
            self.profiler.add_function(Condition.check_string_match)
            self.profiler.add_function(Condition.check_function)
            self.profiler.add_function(Condition.check_list)

        t = Timer()

        # Run itself
        if self.mode == 'h':
            self.profiler.runcall(self.test.run)
        else:
            self.test.run()

        print('Test time: %s' % t.delta())

        if self.mode == 'c':
            import pstats
            import StringIO

            self.profiler.disable()
            sio = StringIO.StringIO()

            ps = pstats.Stats(self.profiler, stream=sio).sort_stats('time')
            ps.print_stats()

            print(sio.getvalue())

        elif self.mode == 'h':
            import hotshot.stats

            print('Processing results...')

            self.profiler.close()
            name = self.info['name']
            stats = hotshot.stats.load(name)
            stats.strip_dirs()
            stats.sort_stats('time', 'calls')
            stats.print_stats(50)

            print('Run "hotshot2calltree -o %s.out %s" to generate the cachegrind file' % (name, name))

        elif self.mode == 'l':
            self.profiler.disable()
            self.profiler.print_stats()
Beispiel #47
0
        properties[i].append(objects[j].moments_hu())
        properties[i].append(objects[j].image())
        properties[i].append(objects[j].label)
        properties[i].append(objects[j].major_axis_length())
        properties[i].append(objects[j].max_intensity())
        properties[i].append(objects[j].mean_intensity())
        properties[i].append(objects[j].min_intensity())
        properties[i].append(objects[j].minor_axis_length())
        properties[i].append(objects[j].moments())
        properties[i].append(objects[j].moments_normalized())
        properties[i].append(objects[j].orientation())
        properties[i].append(objects[j].perimeter())
        properties[i].append(objects[j].solidity())
        properties[i].append(objects[j].weighted_moments_central())
        properties[i].append(objects[j].weighted_centroid())
        properties[i].append(objects[j].weighted_moments_hu())
        properties[i].append(objects[j].weighted_moments())
        properties[i].append(objects[j].weighted_moments_normalized())
    return properties, prop_names


if __name__ == '__main__':
    image = io.imread('test-image.png')
    green = image[..., 1].copy()
    lp = LineProfiler()
    lp.add_function(object_features)
    lp.run('intensity_object_features(green, 100)')
    lp.print_stats()
    lp.dump_stats('profile.lprof')
    print(__file__)