-1

I wish to make a program that will print numbers from 0 to x, and simultaneously count time, and both execute simultaneously in console. How can I do that?

For example, I want to make program which will count time while the computer writes numbers from 0 to x:

import time
import sys

time_counter = 0
number = int(input("NUMBER: "))
counter = 0

while (counter < number):
    sys.stdout.write("NUMBERS: " + str(counter) + '\r')
    counter += 1

sys.stdout.write('\n')
while (counter < number):
    sys.stdout.write("TIME COUNTER: " + str(time_counter) + '\r')
    time.sleep(1)
    time_counter += 1

I want to these two while code blocks to execute simultaneously.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

2 Answers2

1

First of all, I'm not exactly clear on what you are trying to achieve (the general purpose of the code).

But for the specific code question, you could try it with a single while loop, maybe like this:

import time

stop_number = int(input("NUMBER: "))

num_counter = 0
time_counter = 0

while num_counter < stop_number:
    print(num_counter, time_counter)

    time.sleep(1)

    num_counter += 1
    time_counter += 1

I don't know how to easily print on two different lines in the terminal, so my code just prints on the same line, one line per iteration. If you want to go into that, have a look at this answer and other similar ones.

Ralf
  • 16,086
  • 4
  • 44
  • 68
0

If you want to measure the time it takes to print the number, you can try the timeit module:

import timeit

def f1(stop_number):
    num_counter = 0

    print('Numbers:')
    while num_counter < stop_number:
        print(num_counter, end=' ', flush=True)
        num_counter += 1
    print()

if __name__ == '__main__':
    stop_number = int(input("NUMBER: "))

    t = timeit.timeit(
        stmt='f1({})'.format(stop_number),
        setup='from __main__ import f1',
        number=1000)
    print()
    print('The statement took in average {} seconds to run.'.format(t))

Or if you want, you can also measure the time difference using time.perf_counter():

import time

stop_number = int(input("NUMBER: "))

start_time = time.perf_counter()

num_counter = 0
while num_counter < stop_number:
    print(num_counter)
    num_counter += 1

end_time = time.perf_counter()
print('The code took {} seconds to run.'.format(end_time - start_time))

Note that printing output consumes a lot of time; just the iteration without printing will take a lot less time.

Ralf
  • 16,086
  • 4
  • 44
  • 68