0

I need a piece of Python code that loads (stresses?) CPU for a short moment. I would also like to get some output like counter printed during stressing CPU. Seems simple enough:

N=32

def fib(n):
    if n < 2:
        return 1
    else:
        return fib(n-1) + fib(n-2)


def main(num):
    for i in range(1, num+1):
        fib(N)
        print(i, end=' ')

if __name__ == '__main__':
    main(10)

However, when I use print(i, end=' '), it does not output counter as it executes, it only outputs 1 2 3 4 5 6 7 8 9 10 once it completes.

If I use regular print (print(i)) it prints the counter as it goes.

First of all, I want to know why this weird effect takes place, and second, how to make print with end behave in this regard like print without end keyword.

LetMeSOThat4U
  • 6,470
  • 10
  • 53
  • 93

1 Answers1

1

The print operation is buffered by default, but you can force it to flush the buffer and print immediately. See the Python documentation for more info.

print("foobar", flush=True)
jkr
  • 17,119
  • 2
  • 42
  • 68