Published 27 Jun, 2022

Python - How to print iterations per second?

Category Python
Modified : Nov 16, 2022

I have a small Python script which sends POST requests to a server and gets their response.

It iterates 10000 times, and I managed to print the current progress in command prompt using:


at the end of each loop.

Because this involves interaction with a webserver, I would like to show the current average speed next to this too (updated like every 2 seconds).

An example at the bottom of the command prompt would then be like this:

(1245/10000), 6.3 requests/second

How do I achieve this?


There are 3 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Loops, Python, Performance, Cmd, Progress. These have been categorized in sections for a clear and precise explanation.


You can get a total average number of events per second like this:

#!/usr/bin/env python3

import time
import datetime as dt

start_time =
i = 0
    time_diff = - start_time
    i += 1
    print(i / time_diff)

Which in this example would print approximately 10. Please note that I used a timestamp method of datetime which is only availble in Python 3.

Now, if you would like to calculate the "current" number of events per second, say over the last 10 events, you can do it like this:

#!/usr/bin/env python3

import time
import datetime as dt

last_time =
diffs = []

    # Add new time diff to list
    new_time =
    diffs.append(new_time - last_time)
    last_time = new_time

    # Clip the list
    if len(diffs) > 10:
        diffs = diffs[-10:]

    print(len(diffs) / sum(diffs))

Here, I'm keeping a list of durations of last 10 iterations over which I can then use to get the average number of events per second.


You can use the tqdm library for this. A simple example for this is

from tqdm import tqdm
for i in tqdm(range(1e20)):

This will print the current iteration, iterations/second, ETA and a nice progress bar


 21%|████████████████████  21/100 [01:45<04:27,  3.39s/it]


It depends whether your requests are sent synchronously or asynchronously.

For synchronous sending, tqdm library provides the required statistics.

For asynchronous sending you should wrap your request sending code with a code saving the time it took for each request to be sent, and as a callback update a global object that holds the statistics and updates it to screen. The implementation depends on the library you use for the asynchronous sending.