0

I am fairly new to python and have been trying to make a program that prints a string one character at a time. I was originally using time.sleep() for the delay but it was very inconsistent and looked choppy. I now use time.clock() and compare it after the character is printed. It works better but is still choppy at times. Is there a very consistent method of timekeeping in python?

My code:

def typePrint(string, sec):
  from time import clock
  for char in string:
    strt = clock()
    print(char, end='', flush=True)
    while clock() - strt < sec:
      pass
  print()
martineau
  • 119,623
  • 25
  • 170
  • 301
Joyal Mathew
  • 614
  • 7
  • 24
  • What do you consider 'choppy'? – zwer Sep 20 '18 at 22:34
  • 1
    I'm concerned that the actual problem is time-slicing on your system. If you're using the built-in timing methods (sleep / clock), your functional performance should be smooth. – Prune Sep 20 '18 at 22:38
  • @zwer , the time in between the letters being printed is inconsistent and varies by a noticeable amount. – Joyal Mathew Sep 20 '18 at 23:18
  • 2
    That `while clock() - strt < sec: pass` is wasting a lot of CPU cycles. It's probably a Good Idea to avoid doing stuff like that. ;) [This answer of mine](https://stackoverflow.com/a/51390651/4014959) might give you some ideas about how to do fairly precise delays. – PM 2Ring Sep 20 '18 at 23:35
  • 1
    @PM2Ring thanks that answer helped me. It works a lot better now! – Joyal Mathew Sep 22 '18 at 15:38

1 Answers1

0

Here's another implementation using time.sleep:

def typePrint(string, sec):
    from time import sleep

    for char in string:
        print(char, end="", flush=True)
        sleep(sec)
    print()

Making a syscall (like time.clock) in a busy loop is a good way to get flaky behavior, especially on a loaded system.

Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65