• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python cgutils.if_likely函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: timedelta_mod_timedelta

    def timedelta_mod_timedelta(context, builder, sig, args):
        # inspired by https://github.com/numpy/numpy/blob/fe8072a12d65e43bd2e0b0f9ad67ab0108cc54b3/numpy/core/src/umath/loops.c.src#L1424
        # alg is basically as `a % b`:
        # if a or b is NaT return NaT
        # elseif b is 0 return NaT
        # else pretend a and b are int and do pythonic int modulus

        [va, vb] = args
        [ta, tb] = sig.args
        not_nan = are_not_nat(builder, [va, vb])
        ll_ret_type = context.get_value_type(sig.return_type)
        ret = alloc_timedelta_result(builder)
        builder.store(NAT, ret)
        zero = Constant.int(ll_ret_type, 0)
        with cgutils.if_likely(builder, not_nan):
            va, vb = normalize_timedeltas(context, builder, va, vb, ta, tb)
            # is the denominator zero or NaT?
            denom_ok = builder.not_(builder.icmp_signed('==', vb, zero))
            with cgutils.if_likely(builder, denom_ok):
                # is either arg negative?
                vapos = builder.icmp_signed('>', va, zero)
                vbpos = builder.icmp_signed('>', vb, zero)
                rem = builder.srem(va, vb)
                cond = builder.or_(builder.and_(vapos, vbpos),
                                   builder.icmp_signed('==', rem, zero))
                with builder.if_else(cond) as (then, otherwise):
                    with then:
                        builder.store(rem, ret)
                    with otherwise:
                        builder.store(builder.add(rem, vb), ret)

        res = builder.load(ret)
        return impl_ret_untracked(context, builder, sig.return_type, res)
开发者ID:numba,项目名称:numba,代码行数:33,代码来源:npdatetime.py


示例2: timedelta_floor_div_timedelta

 def timedelta_floor_div_timedelta(context, builder, sig, args):
     [va, vb] = args
     [ta, tb] = sig.args
     ll_ret_type = context.get_value_type(sig.return_type)
     not_nan = are_not_nat(builder, [va, vb])
     ret = cgutils.alloca_once(builder, ll_ret_type, name='ret')
     zero = Constant.int(ll_ret_type, 0)
     one = Constant.int(ll_ret_type, 1)
     builder.store(zero, ret)
     with cgutils.if_likely(builder, not_nan):
         va, vb = normalize_timedeltas(context, builder, va, vb, ta, tb)
         # is the denominator zero or NaT?
         denom_ok = builder.not_(builder.icmp_signed('==', vb, zero))
         with cgutils.if_likely(builder, denom_ok):
             # is either arg negative?
             vaneg = builder.icmp_signed('<', va, zero)
             neg = builder.or_(vaneg, builder.icmp_signed('<', vb, zero))
             with builder.if_else(neg) as (then, otherwise):
                 with then:  # one or more value negative
                     with builder.if_else(vaneg) as (negthen, negotherwise):
                         with negthen:
                             top = builder.sub(va, one)
                             div = builder.sdiv(top, vb)
                             builder.store(div, ret)
                         with negotherwise:
                             top = builder.add(va, one)
                             div = builder.sdiv(top, vb)
                             builder.store(div, ret)
                 with otherwise:
                     div = builder.sdiv(va, vb)
                     builder.store(div, ret)
     res = builder.load(ret)
     return impl_ret_untracked(context, builder, sig.return_type, res)
开发者ID:numba,项目名称:numba,代码行数:33,代码来源:npdatetime.py


示例3: raise_error

    def raise_error(self, builder, api, status):
        """
        Given a non-ok *status*, raise the corresponding Python exception.
        """
        bbend = builder.function.append_basic_block()

        with builder.if_then(status.is_user_exc):
            # Unserialize user exception.
            # Make sure another error may not interfere.
            api.err_clear()
            exc = api.unserialize(status.excinfoptr)
            with cgutils.if_likely(builder,
                                   cgutils.is_not_null(builder, exc)):
                api.raise_object(exc)  # steals ref
            builder.branch(bbend)

        with builder.if_then(status.is_stop_iteration):
            api.err_set_none("PyExc_StopIteration")
            builder.branch(bbend)

        with builder.if_then(status.is_python_exc):
            # Error already raised => nothing to do
            builder.branch(bbend)

        api.err_set_string("PyExc_SystemError",
                           "unknown error when calling native function")
        builder.branch(bbend)

        builder.position_at_end(bbend)
开发者ID:EGQM,项目名称:numba,代码行数:29,代码来源:callconv.py


示例4: _increment_indices

def _increment_indices(context, builder, ndim, shape, indices, end_flag=None):
    zero = context.get_constant(types.intp, 0)
    one = context.get_constant(types.intp, 1)

    bbend = cgutils.append_basic_block(builder, 'end_increment')

    if end_flag is not None:
        builder.store(cgutils.false_byte, end_flag)

    for dim in reversed(range(ndim)):
        idxptr = cgutils.gep(builder, indices, dim)
        idx = builder.add(builder.load(idxptr), one)

        count = shape[dim]
        in_bounds = builder.icmp(lc.ICMP_SLT, idx, count)
        with cgutils.if_likely(builder, in_bounds):
            builder.store(idx, idxptr)
            builder.branch(bbend)
        builder.store(zero, idxptr)

    if end_flag is not None:
        builder.store(cgutils.true_byte, end_flag)
    builder.branch(bbend)

    builder.position_at_end(bbend)
开发者ID:PierreBizouard,项目名称:numba,代码行数:25,代码来源:arrayobj.py


示例5: iternext_specific

            def iternext_specific(self, context, builder, arrty, arr, result):
                zero = context.get_constant(types.intp, 0)
                one = context.get_constant(types.intp, 1)

                ndim = arrty.ndim
                nitems = arr.nitems

                index = builder.load(self.index)
                is_valid = builder.icmp(lc.ICMP_SLT, index, nitems)
                result.set_valid(is_valid)

                with cgutils.if_likely(builder, is_valid):
                    ptr = builder.load(self.pointer)
                    value = context.unpack_value(builder, arrty.dtype, ptr)
                    if kind == 'flat':
                        result.yield_(value)
                    else:
                        # ndenumerate(): fetch and increment indices
                        indices = self.indices
                        idxvals = [builder.load(cgutils.gep(builder, indices, dim))
                                   for dim in range(ndim)]
                        idxtuple = cgutils.pack_array(builder, idxvals)
                        result.yield_(
                            cgutils.make_anonymous_struct(builder, [idxtuple, value]))
                        _increment_indices_array(context, builder, arrty, arr, indices)

                    index = builder.add(index, one)
                    builder.store(index, self.index)
                    ptr = cgutils.pointer_add(builder, ptr, self.stride)
                    builder.store(ptr, self.pointer)
开发者ID:PierreBizouard,项目名称:numba,代码行数:30,代码来源:arrayobj.py


示例6: timedelta_sub_impl

def timedelta_sub_impl(context, builder, sig, args):
    [va, vb] = args
    [ta, tb] = sig.args
    ret = alloc_timedelta_result(builder)
    with cgutils.if_likely(builder, are_not_nat(builder, [va, vb])):
        va = scale_timedelta(context, builder, va, ta, sig.return_type)
        vb = scale_timedelta(context, builder, vb, tb, sig.return_type)
        builder.store(builder.sub(va, vb), ret)
    return builder.load(ret)
开发者ID:genba,项目名称:numba,代码行数:9,代码来源:npdatetime.py


示例7: iternext_numpy_flatiter

def iternext_numpy_flatiter(context, builder, sig, args, result):
    [flatiterty] = sig.args
    [flatiter] = args

    flatitercls = make_array_flat_cls(flatiterty)
    flatiter = flatitercls(context, builder, value=flatiter)

    arrty = flatiterty.array_type
    arrcls = context.make_array(arrty)
    arr = arrcls(context, builder, value=builder.load(flatiter.array))

    ndim = arrty.ndim
    shapes = cgutils.unpack_tuple(builder, arr.shape, ndim)
    indptr = flatiter.iters

    # Load indices and check if they are valid
    indices = []
    is_valid = cgutils.true_bit
    zero = context.get_constant(types.intp, 0)
    one = context.get_constant(types.intp, 1)
    for ax in range(ndim):
        axsize = shapes[ax]
        idxptr = builder.gep(indptr, [context.get_constant(types.intp, ax)])
        idx = builder.load(idxptr)
        ax_valid = builder.icmp(lc.ICMP_SLT, idx, axsize)

        indices.append(idx)
        is_valid = builder.and_(is_valid, ax_valid)

    result.set_valid(is_valid)

    with cgutils.if_likely(builder, is_valid):
        # Get yielded value
        valptr = cgutils.get_item_pointer(builder, arrty, arr, indices)
        yield_value = builder.load(valptr)
        result.yield_(yield_value)

        # Increment iterator indices
        carry_flags = [cgutils.true_bit]
        for ax, (idx, axsize) in reversed(list(enumerate(zip(indices,
                                                             shapes)))):
            idxptr = builder.gep(indptr, [context.get_constant(types.intp, ax)])
            lastcarry = carry_flags[-1]
            idxp1 = builder.add(idx, one)
            carry = builder.icmp(lc.ICMP_SGE, idxp1, axsize)
            idxfinal = builder.select(lastcarry,
                                      builder.select(carry, zero, idxp1),
                                      idx)
            builder.store(idxfinal, idxptr)
            carry_flags.append(builder.and_(carry, lastcarry))

        with cgutils.if_unlikely(builder, carry_flags[-1]):
            # If we have iterated all elements,
            # Set first index to out-of-bound
            idxptr = builder.gep(indptr, [context.get_constant(types.intp, 0)])
            builder.store(shapes[0], idxptr)
开发者ID:genba,项目名称:numba,代码行数:56,代码来源:arrayobj.py


示例8: list_pack

 def list_pack(self, items):
     n = len(items)
     seq = self.list_new(self.context.get_constant(types.intp, n))
     not_null = cgutils.is_not_null(self.builder, seq)
     with cgutils.if_likely(self.builder, not_null):
         for i in range(n):
             idx = self.context.get_constant(types.intp, i)
             self.incref(items[i])
             self.list_setitem(seq, idx, items[i])
     return seq
开发者ID:johandroid,项目名称:numba,代码行数:10,代码来源:pythonapi.py


示例9: impl

 def impl(context, builder, dt_arg, dt_unit,
          td_arg, td_unit, ret_unit):
     ret = alloc_timedelta_result(builder)
     with cgutils.if_likely(builder, are_not_nat(builder, [dt_arg, td_arg])):
         dt_arg = convert_datetime_for_arith(builder, dt_arg,
                                             dt_unit, ret_unit)
         td_factor = npdatetime.get_timedelta_conversion_factor(td_unit, ret_unit)
         td_arg = scale_by_constant(builder, td_arg, td_factor)
         ret_val = getattr(builder, ll_op_name)(dt_arg, td_arg)
         builder.store(ret_val, ret)
     return builder.load(ret)
开发者ID:genba,项目名称:numba,代码行数:11,代码来源:npdatetime.py


示例10: dict_pack

 def dict_pack(self, keyvalues):
     """
     Args
     -----
     keyvalues: iterable of (str, llvm.Value of PyObject*)
     """
     dictobj = self.dict_new()
     not_null = cgutils.is_not_null(self.builder, dictobj)
     with cgutils.if_likely(self.builder, not_null):
         for k, v in keyvalues:
             self.dict_setitem_string(dictobj, k, v)
     return dictobj
开发者ID:johandroid,项目名称:numba,代码行数:12,代码来源:pythonapi.py


示例11: build_wrapper

    def build_wrapper(self, api, builder, closure, args, kws):
        nargs = len(self.fndesc.args)
        keywords = self.make_keywords(self.fndesc.args)
        fmt = self.make_const_string("O" * nargs)

        objs = [api.alloca_obj() for _ in range(nargs)]
        parseok = api.parse_tuple_and_keywords(args, kws, fmt, keywords, *objs)

        pred = builder.icmp(lc.ICMP_EQ, parseok, Constant.null(parseok.type))
        with cgutils.if_unlikely(builder, pred):
            builder.ret(api.get_null_object())

        # Block that returns after erroneous argument unboxing/cleanup
        endblk = cgutils.append_basic_block(builder, "arg.end")
        with cgutils.goto_block(builder, endblk):
            builder.ret(api.get_null_object())

        cleanup_manager = _ArgManager(builder, api, endblk, nargs)

        innerargs = []
        for obj, ty in zip(objs, self.fndesc.argtypes):
            val = cleanup_manager.add_arg(obj, ty)
            innerargs.append(val)

        if self.release_gil:
            cleanup_manager = _GilManager(builder, api, cleanup_manager)

        # The wrapped function doesn't take a full closure, only
        # the Environment object.
        env = self.context.get_env_from_closure(builder, closure)

        status, res = self.context.call_function(builder, self.func,
                                                 self.fndesc.restype,
                                                 self.fndesc.argtypes,
                                                 innerargs, env)
        # Do clean up
        cleanup_manager.emit_cleanup()

        # Determine return status
        with cgutils.if_likely(builder, status.ok):
            with cgutils.ifthen(builder, status.none):
                api.return_none()

            retval = api.from_native_return(res, self.fndesc.restype)
            builder.ret(retval)

        with cgutils.ifthen(builder, builder.not_(status.exc)):
            # !ok && !exc
            # User exception raised
            self.make_exception_switch(api, builder, status.code)

        # !ok && exc
        builder.ret(api.get_null_object())
开发者ID:ymarfoq,项目名称:outilACVDesagregation,代码行数:53,代码来源:callwrapper.py


示例12: build_wrapper

    def build_wrapper(self, api, builder, closure, args, kws):
        nargs = len(self.fndesc.args)

        objs = [api.alloca_obj() for _ in range(nargs)]
        parseok = api.unpack_tuple(args, self.fndesc.qualname, nargs, nargs, *objs)

        pred = builder.icmp(lc.ICMP_EQ, parseok, Constant.null(parseok.type))
        with cgutils.if_unlikely(builder, pred):
            builder.ret(api.get_null_object())

        # Block that returns after erroneous argument unboxing/cleanup
        endblk = builder.append_basic_block("arg.end")
        with builder.goto_block(endblk):
            builder.ret(api.get_null_object())

        cleanup_manager = _ArgManager(self.context, builder, api, endblk, nargs)

        innerargs = []
        for obj, ty in zip(objs, self.fndesc.argtypes):
            val = cleanup_manager.add_arg(obj, ty)
            innerargs.append(val)

        if self.release_gil:
            cleanup_manager = _GilManager(builder, api, cleanup_manager)

        # Extract the Environment object from the Closure
        envptr, env_manager = self.get_env(api, builder, closure)

        status, retval = self.context.call_conv.call_function(
            builder, self.func, self.fndesc.restype, self.fndesc.argtypes,
            innerargs, envptr)
        # Do clean up
        self.debug_print(builder, "# callwrapper: emit_cleanup")
        cleanup_manager.emit_cleanup()
        self.debug_print(builder, "# callwrapper: emit_cleanup end")

        # Determine return status
        with cgutils.if_likely(builder, status.is_ok):
            # Ok => return boxed Python value
            with builder.if_then(status.is_none):
                api.return_none()

            retty = self._simplified_return_type()
            obj = api.from_native_return(retval, retty, env_manager)
            builder.ret(obj)

        with builder.if_then(builder.not_(status.is_python_exc)):
            # User exception raised
            self.make_exception_switch(api, builder, status)

        # Error out
        builder.ret(api.get_null_object())
开发者ID:GaZ3ll3,项目名称:numba,代码行数:52,代码来源:callwrapper.py


示例13: timedelta_over_timedelta

def timedelta_over_timedelta(context, builder, sig, args):
    [va, vb] = args
    [ta, tb] = sig.args
    not_nan = are_not_nat(builder, [va, vb])
    ll_ret_type = context.get_value_type(sig.return_type)
    ret = cgutils.alloca_once(builder, ll_ret_type, name='ret')
    builder.store(Constant.real(ll_ret_type, float('nan')), ret)
    with cgutils.if_likely(builder, not_nan):
        va, vb = normalize_timedeltas(context, builder, va, vb, ta, tb)
        va = builder.sitofp(va, ll_ret_type)
        vb = builder.sitofp(vb, ll_ret_type)
        builder.store(builder.fdiv(va, vb), ret)
    return builder.load(ret)
开发者ID:genba,项目名称:numba,代码行数:13,代码来源:npdatetime.py


示例14: datetime_minus_datetime

def datetime_minus_datetime(context, builder, sig, args):
    va, vb = args
    ta, tb = sig.args
    unit_a = ta.unit
    unit_b = tb.unit
    ret_unit = sig.return_type.unit
    ret = alloc_timedelta_result(builder)
    with cgutils.if_likely(builder, are_not_nat(builder, [va, vb])):
        va = convert_datetime_for_arith(builder, va, unit_a, ret_unit)
        vb = convert_datetime_for_arith(builder, vb, unit_b, ret_unit)
        ret_val = builder.sub(va, vb)
        builder.store(ret_val, ret)
    return builder.load(ret)
开发者ID:genba,项目名称:numba,代码行数:13,代码来源:npdatetime.py


示例15: build_wrapper

    def build_wrapper(self, api, builder, closure, args, kws):
        nargs = len(self.fndesc.args)
        keywords = self.make_keywords(self.fndesc.args)
        fmt = self.make_const_string("O" * nargs)

        objs = [api.alloca_obj() for _ in range(nargs)]
        parseok = api.parse_tuple_and_keywords(args, kws, fmt, keywords, *objs)

        pred = builder.icmp(lc.ICMP_EQ, parseok, Constant.null(parseok.type))
        with cgutils.if_unlikely(builder, pred):
            builder.ret(api.get_null_object())

        innerargs = []
        cleanups = []
        for obj, ty in zip(objs, self.fndesc.argtypes):
            #api.context.debug_print(builder, "%s -> %s" % (obj, ty))
            #api.print_object(builder.load(obj))
            val, dtor = api.to_native_arg(builder.load(obj), ty)
            innerargs.append(val)
            cleanups.append(dtor)

        # The wrapped function doesn't take a full closure, only
        # the Environment object.
        env = self.context.get_env_from_closure(builder, closure)

        status, res = self.context.call_function(builder, self.func,
                                                 self.fndesc.restype,
                                                 self.fndesc.argtypes,
                                                 innerargs, env)

        # Do clean up
        for dtor in cleanups:
            dtor()

        # Determine return status

        with cgutils.if_likely(builder, status.ok):
            with cgutils.ifthen(builder, status.none):
                api.return_none()

            retval = api.from_native_return(res, self.fndesc.restype)
            builder.ret(retval)

        with cgutils.ifthen(builder, builder.not_(status.exc)):
            # !ok && !exc
            # User exception raised
            self.make_exception_switch(api, builder, status.code)

        # !ok && exc
        builder.ret(api.get_null_object())
开发者ID:ASPP,项目名称:numba,代码行数:50,代码来源:callwrapper.py


示例16: _timedelta_times_number

def _timedelta_times_number(context, builder, td_arg, td_type,
                            number_arg, number_type, return_type):
    ret = alloc_timedelta_result(builder)
    with cgutils.if_likely(builder, is_not_nat(builder, td_arg)):
        if isinstance(number_type, types.Float):
            val = builder.sitofp(td_arg, number_arg.type)
            val = builder.fmul(val, number_arg)
            val = builder.fptosi(val, TIMEDELTA64)
        else:
            val = builder.mul(td_arg, number_arg)
        # The scaling is required for ufunc np.multiply() with an explicit
        # output in a different unit.
        val = scale_timedelta(context, builder, val, td_type, return_type)
        builder.store(val, ret)
    return builder.load(ret)
开发者ID:genba,项目名称:numba,代码行数:15,代码来源:npdatetime.py


示例17: iternext_zip

def iternext_zip(context, builder, sig, args, result):
    genty, = sig.args
    gen, = args
    # XXX We should link with the generator's library.
    # Currently, this doesn't make a difference as the library has already
    # been linked for the generator init function.
    impl = context.get_generator_impl(genty)
    status, retval = impl(context, builder, sig, args)
    with cgutils.if_likely(builder, status.is_ok):
        result.set_valid(True)
        result.yield_(retval)
    with cgutils.if_unlikely(builder, status.is_stop_iteration):
        result.set_exhausted()
    with cgutils.if_unlikely(builder, builder.and_(status.is_error, builder.not_(status.is_stop_iteration))):
        context.call_conv.return_status_propagate(builder, status)
开发者ID:gyenney,项目名称:Tools,代码行数:15,代码来源:iterators.py


示例18: iternext_zip

def iternext_zip(context, builder, sig, args, result):
    genty, = sig.args
    gen, = args
    impl = context.get_generator_impl(genty)
    status, retval = impl(context, builder, sig, args)
    context.add_linking_libs(getattr(impl, 'libs', ()))

    with cgutils.if_likely(builder, status.is_ok):
        result.set_valid(True)
        result.yield_(retval)
    with cgutils.if_unlikely(builder, status.is_stop_iteration):
        result.set_exhausted()
    with cgutils.if_unlikely(builder,
                             builder.and_(status.is_error,
                                          builder.not_(status.is_stop_iteration))):
        context.call_conv.return_status_propagate(builder, status)
开发者ID:numba,项目名称:numba,代码行数:16,代码来源:iterators.py


示例19: to_native_buffer

    def to_native_buffer(self, obj, typ):
        buf = self.alloca_buffer()
        res = self.get_buffer(obj, buf)
        is_error = cgutils.is_not_null(self.builder, res)

        nativearycls = self.context.make_array(typ)
        nativeary = nativearycls(self.context, self.builder)
        aryptr = nativeary._getpointer()

        with cgutils.if_likely(self.builder, self.builder.not_(is_error)):
            ptr = self.builder.bitcast(aryptr, self.voidptr)
            self.numba_buffer_adaptor(buf, ptr)

        def cleanup():
            self.release_buffer(buf)

        return NativeValue(self.builder.load(aryptr), is_error=is_error,
                           cleanup=cleanup)
开发者ID:molodiuc,项目名称:numba,代码行数:18,代码来源:pythonapi.py


示例20: make_exception_switch

    def make_exception_switch(self, api, builder, status):
        """
        Handle user exceptions.  Unserialize the exception info and raise it.
        """
        code = status.code
        # Handle user exceptions
        with builder.if_then(status.is_user_exc):
            exc = api.unserialize(status.excinfoptr)
            with cgutils.if_likely(builder, cgutils.is_not_null(builder, exc)):
                api.raise_object(exc)  # steals ref
            builder.ret(api.get_null_object())

        with builder.if_then(status.is_stop_iteration):
            api.err_set_none("PyExc_StopIteration")
            builder.ret(api.get_null_object())

        msg = "unknown error in native function: %s" % self.fndesc.mangled_name
        api.err_set_string("PyExc_SystemError", msg)
开发者ID:shivamvats,项目名称:numba,代码行数:18,代码来源:callwrapper.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python cgutils.if_unlikely函数代码示例发布时间:2022-05-27
下一篇:
Python cgutils.guard_zero函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap