Search code examples
pythonpython-3.xtkintertimechess

Time between consecutive executions of a single function in Python


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.


Solution

  • 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()