0

I have some code in Python:

# Loading the lowercase alphabet to a list
from string import ascii_lowercase
from random import choice

attempts, alphabet, words_five, failed_words = 0, list(ascii_lowercase), "", []

while 1:
    word = []
    word.append(choice(alphabet))
    word.append(choice(alphabet))
    word.append(choice(alphabet))
    word.append(choice(alphabet))
    word.append(choice(alphabet))
    words_one = str(word).replace(",", "")
    words_two = words_one.replace("[", "")
    words_three = words_two.replace("]", "")
    words_four = words_three.replace("'", "")
    words_five = words_four.replace(" ", "")
    if words_five == "hello":
        break
    elif words_five not in failed_words:
        attempts += 1
        failed_words.append(words_five)
        



print(words_five)
print("Attempts: " + str(attempts))

I wanted to print different statistics, and thought a length on how long the process took would be good. However, I don't fully know how to get at this. Is this possible without using another file/script?

I was going to use the time library to make a stopwatch, however it seems it requires its own function, hard to do when already running the main script.

  • 1
    I don't understand what you think would be the problem with using the `time` module. Can't you take the current time at the beginning and the end of the script and use the difference as result? – mkrieger1 Mar 20 '23 at 23:26
  • Echoing @mkrieger, what prevents you from using the time module? There are multiple ways you can encapsulate the above code snippet: https://stackoverflow.com/q/7370801/420157 – Maverickgugu Mar 20 '23 at 23:42
  • Does this answer your question? [How do I get time of a Python program's execution?](https://stackoverflow.com/questions/1557571/how-do-i-get-time-of-a-python-programs-execution) – MD Mushfirat Mohaimin Mar 25 '23 at 13:36

1 Answers1

0

General

In general you can use the following to time blocks of code execution:

import datetime

start = datetime.datetime.now()

# code you want to time

end = datetime.datetime.now() - start

This will provide you with a datetime.timedelta which is a nice way of displaying differences between two times.

Jupyter Notebook

If you are running your code in a Jupyter Notebook you can use the magic command %%timeit

E.g.

%%timeit

# do a thing

It provides the same functionality as the general case covered above, but also gives you some extended options, such as running the cell multiple times and getting an average execution time.

More details on that command here.

proudfeet
  • 1
  • 2