numba / numba

NumPy aware dynamic Python compiler using LLVM
https://numba.pydata.org/
BSD 2-Clause "Simplified" License
9.73k stars 1.12k forks source link

printf that can be called from Numba jit-decorated function #5679

Open pearu opened 4 years ago

pearu commented 4 years ago

Feature request

Having the following implementation

from numba import extending, cgutils, types
@extending.intrinsic
def printf(typingctx, format_type, *args):
    """printf that can be called from Numba jit-decorated functions.
    """
    if isinstance(format_type, types.StringLiteral):
        sig = nb_types.void(format_type, types.BaseTuple.from_types(args))
        def codegen(context, builder, signature, args):
            cgutils.printf(builder, format_type.literal_value, *args[1:]) 
        return sig, codegen

one can call printf from a jit-decorated function. For instance,

from numba import njit
@njit
def foo(a, b):
    c = 1.3
    printf("in foo, a=%p, b=%i, c=%e\n", a, b, c)

and then

>>> foo(1, 2)
in foo, a=0x1, b=2, c=1.300000e+00

I have found it useful for debugging. If there is interest, where such a codelet should land in numba?

stuartarchibald commented 4 years ago

Thanks for the suggestion. I think this is a good thing to have, but should probably be @overload'd or @register_jitable'd and made to work "kind of the same" when JIT is disabled (i.e. might have to replace the format specifiers to make it work in CPython). As to location, how about numba.misc.utils or similar? There's numba.misc.special already but it's not like this is some special token, it's a useful piece of additional functionality.

quantfreedom commented 10 months ago

@pearu ... does this still work ... i copied what you did and nothing was returned and it also seems that they moved cgutils

pearu commented 10 months ago

@QuantFreedom1022 not likely, for instance, cgutils now lives under numba.core. However, it should be possible to fix the feature for newer numba versions.