简体   繁体   English

如何打印每秒迭代次数?

[英]How to print iterations per second?

I have a small Python script which sends POST requests to a server and gets their response.我有一个小的 Python 脚本,它向服务器发送 POST 请求并得到它们的响应。

It iterates 10000 times, and I managed to print the current progress in command prompt using:它迭代 10000 次,我设法使用以下命令在命令提示符中打印当前进度:

code=current_requestnumber
print('{0}/{1}'.format(str(code),"10000"),end="\r")

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).因为这涉及与网络服务器的交互,所以我也想在此旁边显示当前的平均速度(每 2 秒更新一次)。

An example at the bottom of the command prompt would then be like this:命令提示符底部的示例将如下所示:

(1245/10000), 6.3 requests/second (1245/10000), 6.3 个请求/秒

How do I achieve this?我如何实现这一目标?

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 = dt.datetime.today().timestamp()
i = 0
while(True):
    time.sleep(0.1)
    time_diff = dt.datetime.today().timestamp() - 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.在这个例子中,它会打印大约 10。请注意,我使用了datetimetimestamp方法,该方法仅在 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:现在,如果您想计算每秒的“当前”事件数,比如最近 10 个事件,您可以这样做:

#!/usr/bin/env python3

import time
import datetime as dt

last_time = dt.datetime.today().timestamp()
diffs = []
while(True):
    time.sleep(0.1)

    # Add new time diff to list
    new_time = dt.datetime.today().timestamp()
    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.在这里,我保留了最近 10 次迭代的持续时间列表,然后我可以用它来获得每秒的平均事件数。

You can use the tqdm library for this.您可以为此使用tqdm库。 A simple example for this is一个简单的例子是

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

This will print the current iteration, iterations/second, ETA and a nice progress bar这将打印当前迭代、迭代/秒、ETA 和一个不错的进度条

eg例如

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

With python-progressbar2 you can do it like this:使用python-progressbar2你可以这样做:

import time
import progressbar


widgets = [
    progressbar.Percentage(),
    progressbar.Bar(),
    ' ', progressbar.SimpleProgress(),
    ' ', progressbar.ETA(),
    ' ', progressbar.AdaptiveTransferSpeed(unit='it'),
]

bar = progressbar.ProgressBar(widgets=widgets)
for i in bar(range(100)):
    time.sleep(0.2)
    bar.update(i)

This does roughly what you want I think :)这大致符合我的想法:)

 19%|########                               | 19 of 100 ETA:   0:00:17   4.9 it/s

(disclaimer: I'm the author and maintainer of python-progressbar2 ) (免责声明:我是python-progressbar2的作者和维护者)

Using progress bar 2 here is the solution:在此处使用进度条 2 是解决方案:

import time
import progressbar
widgets = [
    progressbar.Percentage(),
    ' ', progressbar.SimpleProgress(format=f'({progressbar.SimpleProgress.DEFAULT_FORMAT})'),
    ' ', progressbar.Bar(),
    ' ', progressbar.Timer(), ' | '
                              ' ', progressbar.ETA(), ' | ',
    ' ', progressbar.AdaptiveTransferSpeed(unit='it'),
]
bar = progressbar.ProgressBar(widgets=widgets)
for i in bar(range(100)):
    time.sleep(0.1)
    bar.update(i)
100% (100 of 100) |#####| Elapsed Time: 0:00:10 |  Time:  0:00:10 |    9.8 it/s

see discussion for details, acknowledgement to the fantastic forum the maintainers of progressbar 2 have: https://github.com/WoLpH/python-progressbar/discussions/253有关详细信息,请参阅讨论,感谢progressbar 2 维护者的精彩论坛: https : //github.com/WoLpH/python-progressbar/discussions/253

Count finished requests and divide it by the time the program took to execute already?计算完成的请求并将其除以程序已经执行的时间?

time.time will be useful for getting the time. time.time 将有助于获取时间。 The rest is just dividing of current_requestnumber by the differnce in seconds since start... That way you get the long term average.其余的只是将 current_requestnumber 除以自开始以来的秒数差异......这样你就可以获得长期平均值。 If you need to quickly show when the speed changes it gets a bit more complicated because you need to count the number of requests for say the last 10 seconds.如果您需要在速度变化时快速显示它会变得有点复杂,因为您需要计算最近 10 秒的请求数量。 (one way is just reset the counter when more than 10 seconds have passed since the last reset) (一种方法是在上次重置后超过 10 秒时重置计数器)

It depends whether your requests are sent synchronously or asynchronously.这取决于您的请求是同步发送还是异步发送。

For synchronous sending, tqdm library provides the required statistics.对于同步发送, tqdm库提供了所需的统计信息。

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.实现取决于您用于异步发送的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM