简体   繁体   中英

How to find out how many times a minute a function is executed in Python?

I have a function and I want to know how many times this function is executed per minute

For example, write every 1 minute:

204 hash/m

This is my function

def test_hash_abc(difficulty):
    x = 0
    while 1:
        y = hashlib.sha256("hello world{}".format(x).encode('utf-8')).hexdigest()
        if y[0:len(difficulty)] == str(difficulty) :
            print(y)
            x+= 1
        else : x+= 1


test_hash_abc('ffff')

cant say about per minute but you can use line_profiler module which have time per hit table on line basis

Your function contains while 1 which is an infinite loop in your case (as you never break out of the loop). I assume you want to see how many times per minute the code under while 1 runs. In that case, try the following:

import hashlib
import time

def test_hash_abc(difficulty):
    x = 0
    counter = 0
    while 1:
        start = time.time()
        while time.time() - start < 60:
            y = hashlib.sha256("hello world{}".format(x).encode('utf-8')).hexdigest()
            if y[0:len(difficulty)] == str(difficulty) :
                print(y)
                x+= 1
            else:
                x+= 1
            counter += 1
        print('{} hash/m'.format(counter))

test_hash_abc('ffff')

Note that removing print(y) will result in a higher execution number per minute.

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