当前位置: 首页>>代码示例>>Python>>正文


Python timeit.reindent函数代码示例

本文整理汇总了Python中timeit.reindent函数的典型用法代码示例。如果您正苦于以下问题:Python reindent函数的具体用法?Python reindent怎么用?Python reindent使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了reindent函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_param_writer_object

def add_param_writer_object(name, base_state, typ, var_type = "", var_index = None, root_node = False):
    var_type1 = "_" + var_type if var_type != "" else ""
    if isinstance(var_index, Number):
        var_index = "uint32_t(" + str(var_index) +")"
    set_varient_index = "serialize(_out, " + var_index +");\n" if var_index is not None else ""
    ret = Template(reindent(4,"""
        ${base_state}__${name}$var_type1 start_${name}$var_type() && {
            $set_varient_index
            return { _out, std::move(_state) };
        }
    """)).substitute(locals())
    if not is_stub(typ) and is_local_type(typ):
        ret += add_param_writer_basic_type(name, base_state, typ, var_type, var_index, root_node)
    if is_stub(typ):
        set_command = "_state.f.end(_out);" if var_type is not "" else ""
        return_command = "{ _out, std::move(_state._parent) }" if var_type is not "" and not root_node else "{ _out, std::move(_state) }"
        ret += Template(reindent(4, """
            template<typename Serializer>
            after_${base_state}__${name} ${name}$var_type(Serializer&& f) && {
                $set_varient_index
                f(writer_of_$typ(_out));
                $set_command
                return $return_command;
            }""")).substitute(locals())
    return ret
开发者ID:TsaiJin,项目名称:scylla,代码行数:25,代码来源:idl-compiler.py

示例2: time_snippet

def time_snippet(line, repeat, number, globals, locals, setup='pass'):
    """ Run timing on piece of code passed in. This code is inspired
    by the %timeit code from Ipython. Any errors in it are of my own
    doing.

    Parameters
    ----------
    line : string
        Source code to be timed. Multiline strings are okay.
    repeat : integer
        Number of time the timing should be repeated. 
    number : integer
        Number of loop iterations to run within a timing run.
    globals : dictionary like object
        Object to use as global scope
    locals : dictionary like object
        Object to use as local scope
    setup : string
        Statements to execute to perform any setup before
        before timing run

    Returns
    -------
    value : float
        Amount of time taken by operation in seconds
    """
    timer = timeit.Timer(timer=timeit.default_timer)
    src = timeit.template % {'stmt' : timeit.reindent(line, 4),
    'setup' : timeit.reindent(setup, 4)}
    code = compile(src, "<foo>", "exec")
    exec code in globals, locals
    timer.inner = locals['inner']
    best = min(timer.repeat(repeat, number)) / number
    return best
开发者ID:deepankarsharma,项目名称:cost-of-python,代码行数:34,代码来源:measure.py

示例3: add_param_writer_basic_type

def add_param_writer_basic_type(name, base_state, typ, var_type = "", var_index = None, root_node = False):
    if isinstance(var_index, Number):
        var_index = "uint32_t(" + str(var_index) +")"
    create_variant_state = Template("auto state = state_of_${base_state}__$name<Output> { start_frame(_out), std::move(_state) };").substitute(locals()) if var_index and root_node else ""
    set_varient_index = "serialize(_out, " + var_index +");\n" if var_index is not None else ""
    set_command = ("_state.f.end(_out);" if not root_node else "state.f.end(_out);") if var_type is not "" else ""
    return_command = "{ _out, std::move(_state._parent) }" if var_type is not "" and not root_node else "{ _out, std::move(_state) }"

    allow_fragmented = False
    if typ in ['bytes', 'sstring']:
        typ += '_view'
        allow_fragmented = True
    else:
        typ = 'const ' + typ + '&'

    writer = Template(reindent(4, """
        after_${base_state}__$name<Output> write_$name$var_type($typ t) && {
            $create_variant_state
            $set_varient_index
            serialize(_out, t);
            $set_command
            return $return_command;
        }""")).substitute(locals())
    if allow_fragmented:
        writer += Template(reindent(4, """
        template<typename FragmentedBuffer>
        GCC6_CONCEPT(requires FragmentRange<FragmentedBuffer>)
        after_${base_state}__$name<Output> write_fragmented_$name$var_type(FragmentedBuffer&& fragments) && {
            $set_varient_index
            serialize_fragmented(_out, std::forward<FragmentedBuffer>(fragments));
            $set_command
            return $return_command;
        }""")).substitute(locals())
    return writer
开发者ID:duarten,项目名称:scylla,代码行数:34,代码来源:idl-compiler.py

示例4: test_reindent_multi

 def test_reindent_multi(self):
     self.assertEqual(timeit.reindent(
         "print()\npass\nbreak", 0),
         "print()\npass\nbreak")
     self.assertEqual(timeit.reindent(
         "print()\npass\nbreak", 4),
         "print()\n    pass\n    break")
开发者ID:0jpq0,项目名称:kbengine,代码行数:7,代码来源:test_timeit.py

示例5: add_view

def add_view(hout, info):
    [cls, namespaces, parent_template_param] = info
    members = get_members(cls)
    for m in members:
        add_variant_read_size(hout, m["type"])

    fprintln(hout, Template("""struct ${name}_view {
    seastar::simple_input_stream v;
    """).substitute({'name' : cls["name"]}))

    if not is_stub(cls["name"]) and is_local_type(cls["name"]):
        fprintln(hout, Template(reindent(4, """
            operator $type() const {
               auto in = v;
               return deserialize(in, boost::type<$type>());
            }
        """)).substitute({'type' : cls["name"]}))

    skip = "" if is_final(cls) else "skip(in, boost::type<size_type>());"
    for m in members:
        full_type = param_view_type(m["type"])
        fprintln(hout, Template(reindent(4, """
            $type $name() const {
               auto in = v;
               $skip
               return deserialize(in, boost::type<$type>());
            }
        """)).substitute({'name' : m["name"], 'type' : full_type, 'skip' : skip}))

        skip = skip + Template("\n       skip(in, boost::type<${type}>());").substitute({'type': full_type})

    fprintln(hout, "};")
    skip_impl = "seastar::simple_input_stream& in = v;\n       " + skip if is_final(cls) else "v.skip(read_frame_size(v));"
    if skip == "":
        skip_impl = ""

    fprintln(hout, Template("""
template<>
inline void skip(seastar::simple_input_stream& v, boost::type<${type}_view>) {
    $skip_impl
}

template<>
struct serializer<${type}_view> {
    template<typename Input>
    static ${type}_view read(Input& v) {
        auto v_start = v;
        auto start_size = v.size();
        skip(v, boost::type<${type}_view>());
        return ${type}_view{v_start.read_substream(start_size - v.size())};
    }
    template<typename Output>
    static void write(Output& out, ${type}_view v) {
        out.write(v.v.begin(), v.v.size());
    }
};
""").substitute({'type' : param_type(cls["name"]), 'skip' : skip, 'skip_impl' : skip_impl}))
开发者ID:TsaiJin,项目名称:scylla,代码行数:57,代码来源:idl-compiler.py

示例6: __init__

 def __init__(self, stmt, setup='pass', timer=timeit.default_timer, globals=globals()):
     # copy of timeit.Timer.__init__
     # similarity index 95%
     self.timer = timer
     stmt  = timeit.reindent(stmt, 8)
     setup = timeit.reindent(setup, 4)
     src   = timeit.template % {'stmt': stmt, 'setup': setup}
     self.src = src # Save for traceback display
     code = compile(src, timeit.dummy_src_name, "exec")
     ns = {}
    #exec code in globals(), ns      -- original timeit code
     exec code in globals, ns    #   -- we use caller-provided globals instead
     self.inner = ns["inner"]
开发者ID:101man,项目名称:sympy,代码行数:13,代码来源:benchmarking.py

示例7: banner

def banner(message):
    host_string = "%s (%s)" % (message, env.host_string)

    print green(reindent("""
    #########################################################################
    ## %s
    #########################################################################
    """ % host_string, 0))
开发者ID:shuoli84,项目名称:jianguo,代码行数:8,代码来源:fabfile.py

示例8: add_optional_node

def add_optional_node(hout, typ):
    global optional_nodes
    full_type = flat_type(typ)
    if full_type in optional_nodes:
        return
    optional_nodes.add(full_type)
    fprintln(hout, Template(reindent(0,"""
struct writer_of_$type {
    bytes_ostream& _out;
    $add_method
};""")).substitute({'type': full_type, 'add_method': optional_add_methods(typ[1][0])}))
开发者ID:TsaiJin,项目名称:scylla,代码行数:11,代码来源:idl-compiler.py

示例9: optional_add_methods

def optional_add_methods(typ):
    res = reindent(4,"""
    void skip()  {
        serialize(_out, false);
    }""")
    if is_basic_type(typ):
        added_type = typ
    elif is_local_type(typ):
        added_type = param_type(typ) + "_view"
    else:
        print("non supported optional type ", typ)
        raise "non supported optional type " + param_type(typ)
    res = res + Template(reindent(4, """
    void write(const $type& obj) {
        serialize(_out, true);
        serialize(_out, obj);
    }""")).substitute({'type' : added_type})
    if is_local_type(typ):
        res = res + Template(reindent(4, """
    writer_of_$type write() {
        serialize(_out, true);
        return {_out};
    }""")).substitute({'type' : param_type(typ)})
    return res
开发者ID:TsaiJin,项目名称:scylla,代码行数:24,代码来源:idl-compiler.py

示例10: add_param_write

def add_param_write(current, base_state, vector = False, root_node = False):
    typ = current["type"]
    res = ""
    name = get_member_name(current["name"])
    if is_basic_type(typ):
        res = res + add_param_writer_basic_type(name, base_state, typ)
    elif is_optional(typ):
            res = res +  Template(reindent(4, """
    after_${basestate}__$name<Output> skip_$name() && {
        serialize(_out, false);
        return { _out, std::move(_state) };
    }""")).substitute({'type': param_type(typ), 'name': name, 'basestate' : base_state})
            if is_basic_type(typ[1][0]):
                res = res + add_param_writer_basic_type(name, base_state, typ[1][0], "", "true")
            elif is_local_type(typ[1][0]):
                res = res + add_param_writer_object(name, base_state[0][1], typ, "", "true")
            else:
                print("non supported optional type ", type[0][1])
    elif is_vector(typ):
        set_size = "_size.set(_out, 0);" if vector else "serialize(_out, size_type(0));"

        res = res +  Template("""
    ${basestate}__$name<Output> start_$name() && {
        return { _out, std::move(_state) };
    }

    after_${basestate}__$name<Output> skip_$name() && {
        $set
        return { _out, std::move(_state) };
    }
""").substitute({'type': param_type(typ), 'name': name, 'basestate' : base_state, 'set' : set_size})
    elif is_local_type(typ):
        res = res + add_param_writer_object(name, base_state, typ)
    elif is_variant(typ):
        for idx, p in enumerate(typ[1]):
            if is_basic_type(p):
                varient_type = param_type(p)
                res = res + add_param_writer_basic_type(name, base_state, varient_type,"_" + varient_type, idx, root_node)
            elif is_variant(p):
                res = res + add_param_writer_object(name, base_state, p, '_' + "variant", idx, root_node)
            elif is_local_type(p):
                res = res + add_param_writer_object(name, base_state, p, '_' + param_type(p), idx, root_node)
    else:
        print ("something is wrong with type", typ)
    return res;
开发者ID:duarten,项目名称:scylla,代码行数:45,代码来源:idl-compiler.py

示例11: add_param_writer_basic_type

def add_param_writer_basic_type(name, base_state, typ, var_type = "", var_index = None, root_node = False):
    if isinstance(var_index, Number):
        var_index = "uint32_t(" + str(var_index) +")"
    set_varient_index = "serialize(_out, " + var_index +");\n" if var_index is not None else ""
    set_command = "_state.f.end(_out);" if var_type is not "" else ""
    return_command = "{ _out, std::move(_state._parent) }" if var_type is not "" and not root_node else "{ _out, std::move(_state) }"

    if typ in ['bytes', 'sstring']:
        typ += '_view'
    else:
        typ = 'const ' + typ + '&'

    return Template(reindent(4, """
        after_${base_state}__$name write_$name$var_type($typ t) && {
            $set_varient_index
            serialize(_out, t);
            $set_command
            return $return_command;
        }""")).substitute(locals())
开发者ID:TsaiJin,项目名称:scylla,代码行数:19,代码来源:idl-compiler.py

示例12: sage_timeit

def sage_timeit(stmt, globals, preparse=None, number = 0, repeat = 3, precision = 3):
    """
    INPUT:
        stmt -- a text string which may
        globals -- evaluate stmt in the context of the globals dictionary
        preparse -- (default: use global preparser default) if True preparse
                    stmt using the Sage preparser.
    EXAMPLES:
        sage: from sage.misc.sage_timeit import sage_timeit
        sage: sage_timeit('3^100000', globals(), preparse=True, number=50)      # random output
        '50 loops, best of 3: 1.97 ms per loop'
        sage: sage_timeit('3^100000', globals(), preparse=False, number=50)     # random output
        '50 loops, best of 3: 67.1 ns per loop'
        sage: a = 10
        sage: sage_timeit('a^2', globals(), number=50)                            # random output
        '50 loops, best of 3: 4.26 us per loop'

    It's usually better to use the timeit object, usually:
        sage: timeit('10^2', number=50)
        50 loops, best of 3: ... per loop

    The input expression can contain newlines:
        sage: from sage.misc.sage_timeit import sage_timeit
        sage: sage_timeit("a = 2\nb=131\nfactor(a^b-1)", globals(), number=10)
        10 loops, best of 3: ... per loop

    Test to make sure that timeit behaves well with output:
        sage: timeit("print 'Hi'", number=50)
        50 loops, best of 3: ... per loop


    Make sure that garbage collection is renabled after an exception
    occurs in timeit.

    TESTS:
        sage: def f(): raise ValueError
        sage: import gc
        sage: gc.isenabled()
        True
        sage: timeit("f()")
        Traceback (most recent call last):
        ...
        ValueError
        sage: gc.isenabled()
        True

    """
    number=int(number)
    repeat=int(repeat)
    precision=int(precision)
    if preparse is None:
        preparse = interpreter.do_preparse
    if preparse:
        stmt = preparser.preparse(stmt)
    if stmt == "":
        return ''

    units = ["s", "ms", "\xc2\xb5s", "ns"]
    scaling = [1, 1e3, 1e6, 1e9]

    timer = timeit_.Timer()

    # this code has tight coupling to the inner workings of timeit.Timer,
    # but is there a better way to achieve that the code stmt has access
    # to the shell namespace?

    src = timeit_.template % {'stmt': timeit_.reindent(stmt, 8),
                             'setup': "pass"}
    code = compile(src, "<magic-timeit>", "exec")
    ns = {}
    exec code in globals, ns
    timer.inner = ns["inner"]


    try:
        import sys
        f = sys.stdout
        sys.stdout = open('/dev/null', 'w')

        if number == 0:
            # determine number so that 0.2 <= total time < 2.0
            number = 1
            for i in range(1, 5):
                number *= 5
                if timer.timeit(number) >= 0.2:
                    break

        best = min(timer.repeat(repeat, number)) / number

    finally:
        sys.stdout.close()
        sys.stdout = f
        import gc
        gc.enable()

    if best > 0.0:
        order = min(-int(math.floor(math.log10(best)) // 3), 3)
    else:
        order = 3
    stats = (number, repeat, precision, best * scaling[order], units[order])
#.........这里部分代码省略.........
开发者ID:pombredanne,项目名称:spd_notebook,代码行数:101,代码来源:sage_timeit.py

示例13: sage_timeit


#.........这里部分代码省略.........

    The input expression can contain newlines (but doctests cannot, so
    we use ``os.linesep`` here)::

        sage: from sage.misc.sage_timeit import sage_timeit
        sage: from os import linesep as CR
        sage: # sage_timeit(r'a = 2\\nb=131\\nfactor(a^b-1)')
        sage: sage_timeit('a = 2' + CR + 'b=131' + CR + 'factor(a^b-1)',
        ...               globals(), number=10)
        10 loops, best of 3: ... per loop

    Test to make sure that ``timeit`` behaves well with output::

        sage: timeit("print 'Hi'", number=50)
        50 loops, best of 3: ... per loop

    If you want a machine-readable output, use the ``seconds=True`` option::

        sage: timeit("print 'Hi'", seconds=True)   # random output
        1.42555236816e-06
        sage: t = timeit("print 'Hi'", seconds=True)
        sage: t     #r random output
        3.6010742187499999e-07

    TESTS:

    Make sure that garbage collection is re-enabled after an exception
    occurs in timeit::

        sage: def f(): raise ValueError
        sage: import gc
        sage: gc.isenabled()
        True
        sage: timeit("f()")
        Traceback (most recent call last):
        ...
        ValueError
        sage: gc.isenabled()
        True
    """
    import timeit as timeit_, time, math, preparser, interpreter
    number=int(number)
    repeat=int(repeat)
    precision=int(precision)
    if preparse is None:
        preparse = interpreter.do_preparse
    if preparse:
        stmt = preparser.preparse(stmt)
    if stmt == "":
        return ''

    units = ["s", "ms", "\xc2\xb5s", "ns"]
    scaling = [1, 1e3, 1e6, 1e9]

    timer = timeit_.Timer()

    # this code has tight coupling to the inner workings of timeit.Timer,
    # but is there a better way to achieve that the code stmt has access
    # to the shell namespace?

    src = timeit_.template % {'stmt': timeit_.reindent(stmt, 8),
                             'setup': "pass"}
    code = compile(src, "<magic-timeit>", "exec")
    ns = {}
    if not globals_dict:
        globals_dict = globals()
    exec code in globals_dict, ns
    timer.inner = ns["inner"]

    try:
        import sys
        f = sys.stdout
        sys.stdout = open('/dev/null', 'w')

        if number == 0:
            # determine number so that 0.2 <= total time < 2.0
            number = 1
            for i in range(1, 5):
                number *= 5
                if timer.timeit(number) >= 0.2:
                    break

        series = [s/number for s in timer.repeat(repeat, number)]
        best = min(series)

    finally:
        sys.stdout.close()
        sys.stdout = f
        import gc
        gc.enable()

    if seconds:
        return best

    if best > 0.0:
        order = min(-int(math.floor(math.log10(best)) // 3), 3)
    else:
        order = 3
    stats = (number, repeat, precision, best * scaling[order], units[order])
    return SageTimeitResult(stats,series=series)
开发者ID:sageb0t,项目名称:testsage,代码行数:101,代码来源:sage_timeit.py

示例14: test_reindent_multi_empty

 def test_reindent_multi_empty(self):
     self.assertEqual(timeit.reindent("\n\n", 0), "\n\n")
     self.assertEqual(timeit.reindent("\n\n", 4), "\n    \n    ")
开发者ID:karthik-panchap,项目名称:python3436,代码行数:3,代码来源:test_timeit.py

示例15: test_reindent_single

 def test_reindent_single(self):
     self.assertEqual(timeit.reindent("pass", 0), "pass")
     self.assertEqual(timeit.reindent("pass", 4), "pass")
开发者ID:karthik-panchap,项目名称:python3436,代码行数:3,代码来源:test_timeit.py


注:本文中的timeit.reindent函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。