0

I tried to run the code:

import time

s = time.time_ns()/1000000
en = time.time_ns()/1000000
ma = 0

while True:
    e = time.time_ns()/1000000
    if s - en >= 1000:
        ma = max(ma,int(1/(e-s)))
        hi = int(((1/(e-s))/ma)*100)
        jk = {hi>50:[int(((hi-50)/50)*255)-255, 255], hi<=50:[255, (((hi)/50)*255)]}[True]
        print("\033[A\033[K\033[A{:>5}fps {:>3}%\033[0;0m".format(int(1/(e-s)), "\033[38;2;{};{};0m{}".format(jk[0], int(jk[1]), hi)))
        en = time.time_ns()/1000000
    time.sleep(0.001)
    s = time.time_ns()/1000000
    

But when hi var was greater than 50 it showed:

95fps 214.2;255;0m58%

And what I want to happen:

75fps 75% (75% is coloured)

Can anyone explain what's happening and how to fix it?


4
  • Add some print and intermediate statements to show all the calculated values as your code progresses.
    – OldBoy
    Commented Jul 4 at 12:14
  • Please, reduce this to a minimal reproducible example. It is not like it is very long as is, and it is indeed reproducible. So, that is already a very short reproducible example. But not exactly minimal: I don't think we need all those machine-dependent things with timing. A simple for i in range(10) printing something in green when i is 4, 5 or 6 should be enough to show your coloring problem.
    – chrslg
    Commented Jul 4 at 12:28
  • Besides, I can't really reproduce your problem (or I didn't understand it). On my machine this does indeed prints some xxx fps y% on each line, sometimes colored, sometimes not. The only problem I can see, related to those ANSI code, is that we go up one line each time (because of those two ESC [ A that over-compensate the implicit \n); I usually prefer simple \r to print this kind of refreshed line (for i in range(10): print(f'{i}', end='\r', flush=True) — flush=True is needed. It is usually implicit with default end='\n', but without that \n you need to explicit it)
    – chrslg
    Commented Jul 4 at 12:34
  • A rapid test printing jk shows that the problem occurs when jk[0] is negative; I think ... - 255 should be 255 - ...
    – Swifty
    Commented Jul 4 at 12:36

0

Browse other questions tagged or ask your own question.