简体   繁体   中英

How can I check the number of iterations per second without using time module?

I would like to check how many iterations are completed per second or how many urllib requests are sent per second, but without slowing down the program at all (which time.sleep() seems to do). This is the program, for example:

while True:
    url = urllib.request.urlopen("google.com")

I would also like for the requests/per second counter to update in miliseconds, so it may print something like

"2.83 requests per second" and then update to "2.93 requests per second" if the loop iterates faster.

I'd use time and a counter to accomplish this. I also added a custom generator (because I couldn't find one within Python's libraries) that allows you to both set and access the i value.

import time, itertools

def byRefCount():
    i = [0]
    while True:
        yield i[0],i
        i[0] += 1

last = time.time()
for i,ref in byRefCount():
    url = urllib.request.urlopen("google.com")

    if time() - last > 1:
        print(i / (time.time()-last))
        ref[0] = 0
        last = time.time()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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