1

Apologies if the question is a little vague, I'll edit it if necessary.

I'm creating a chess game in Python with Tkinter and want to add a chess timer. When a player moves a piece the move() function is called, causing the piece to be moved to the correct square and the turn switches (from black to white and vice-versa) - turn is a list ["W", "B"] that keeps track of whose turn it is.

Called when a player selects a square to move to:

def move():
    #code here
    turn.reverse()

To time each move, I want to measure the time between consecutive execution of the move() function (i.e. time between turn switches).

To summarise:

How can I measure the time between consecutive executions of the same function?

Edit

From the answers I can see that my question was misunderstood, I'm sorry for not clarifying: I'm not looking to measure the time it takes to execute a function (the move() function). I am looking to measure the time between consecutive executions of a function. The answers given here assume I only want to measure the execution time of the function from start to end. You cannot assume that the move() function executes again immediately after it has finished; it is called by clicking a button so there may be a delay (thinking about the move) before the move() function is called again.

Any help would be greatly appreciated.

OmGal
  • 25
  • 6
  • 1
    https://docs.python.org/3/library/time.html#time.monotonic – spectras Jul 25 '18 at 11:11
  • 1
    Possible duplicate of [How to measure time taken between lines of code in python?](https://stackoverflow.com/questions/14452145/how-to-measure-time-taken-between-lines-of-code-in-python) – zwer Jul 25 '18 at 11:13
  • ... or possible duplicate of [Python time measure function](https://stackoverflow.com/questions/5478351/python-time-measure-function) – Kay Jul 25 '18 at 11:15
  • @Kay Does that measure only the execution time of the function or the time until it is next called? – OmGal Jul 25 '18 at 11:19
  • What our comments suggest is that it looks like you didn't properly research your question first, as other SO users have posted about problems that sound very similar to yours before you. You will have to check yourself if a "possible duplicate" can help you solve your problem (hence "possible"), and next time you should do the research before posting. – Kay Jul 25 '18 at 11:24

1 Answers1

2

You can use time module of python. If i understood your question properly, Something like this can be done:

import time
initial_time = time.monotonic()
def move():
    #code here
    time_gap = time.monotonic() - initial_time
    print(time_gap)
    initial_time = time.monotonic()
    turn.reverse()
Sasuke_214
  • 69
  • 1
  • 4