TiimeIrre
TiimeIrre

Reputation: 223

To count a time of program execution that includes console input, in Python 3

For example, there is a program that is designed to do something with data inserted via Run Console. Something like this:

The program counts a number of actions necessary to make the number of elements in each container equal by adding 1 element to k containers, starting from the first one. If it is impossible, output is -1. n is a number of containers, a is an amount of elements in each container.

n = int(input())
a = list(map(int, input().split()))
i = 1
k = 1
actions = 0
while i < n:
    if a[i] < a[i - 1]:
        actions = -1
        break
    elif a[i] == a[i - 1]:
        i += 1
        k += 1
    elif a[i] > a[i - 1]:
        for j in range(k):
            a[j] += 1
            j += 1
        actions += 1
print(actions)

I have some problem with time limit of execution, as numbers in a are limited by 10**9, and my time limit is 2 seconds only. So I've decided to count the execution time, to watch its behaviour with different variables.

But all the methods I found to count the program execution time include the time to input in Run Console. And, you know, I can think for a number of seconds which data to input this time; so I need to count only the time of calculation, without the time of input. Does anyone know how to implement that?

P.S.: if someone gives me a tip on how to make the program mentioned above not to count for months with the input like:

5
1 100 800 90000 1000000

I will be sincerely grateful.

Upvotes: 1

Views: 70

Answers (1)

Ryabchenko Alexander
Ryabchenko Alexander

Reputation: 12460

try this code

import datetime

n = int(input())
a = list(map(int, input().split()))
start_time = datetime.now()
i = 1
k = 1
actions = 0
while i < n:
    if a[i] < a[i - 1]:
        actions = -1
        break
    elif a[i] == a[i - 1]:
        i += 1
        k += 1
    elif a[i] > a[i - 1]:
        for j in range(k):
            a[j] += 1
            j += 1
        actions += 1
print(actions)
print(datetime.now() - start_time)  # time consumed on run

Upvotes: 1

Related Questions