Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flush stdout inside numba jitted function

Apparently numba supports neither sys.stdout.flush nor print("", flush=True).

What is a good way to flush "prints" inside a jitted function?

like image 933
nivniv Avatar asked May 25 '17 16:05

nivniv


People also ask

What is Nopython in Numba?

nopython. Numba has two compilation modes: nopython mode and object mode. The former produces much faster code, but has limitations that can force Numba to fall back to the latter. To prevent Numba from falling back, and instead raise an error, pass nopython=True .

Can Numba handle strings?

Numba supports (Unicode) strings in Python 3. Strings can be passed into nopython mode as arguments, as well as constructed and returned from nopython mode. As in Python, slices (even of length 1) return a new, reference counted string.

How does Numba NJIT work?

Numba reads the Python bytecode for a decorated function and combines this with information about the types of the input arguments to the function. It analyzes and optimizes your code, and finally uses the LLVM compiler library to generate a machine code version of your function, tailored to your CPU capabilities.


1 Answers

You can use the objmode() context manager to use code which is not supported in numba’s nopython JIT mode:

import numba

@numba.njit
def f(x):
    x *= 2
    with numba.objmode():
        print(x, flush=True)
    return x + 1

print(f'f(7) = {f(7)}')
# 14
# f(7) = 15

As noted in the documentation, this should only be used outside of performance-critical code sections due to the overhead involved.

Note: I don’t think this was available when the question was originally asked in 2017.

like image 79
Socob Avatar answered Oct 11 '22 09:10

Socob