【问题标题】:How to find out how many times a minute a function is executed in Python?如何找出一个函数在 Python 中每分钟执行多少次?
【发布时间】:2021-04-19 22:16:54
【问题描述】:
我有一个函数,我想知道这个函数每分钟执行多少次
例如,每1分钟写一次:
204 哈希/m
这是我的功能
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')
【问题讨论】:
标签:
python
python-3.x
hash
hex
mining
【解决方案1】:
您的函数包含 while 1 在您的情况下这是一个无限循环(因为您永远不会跳出循环)。我假设您想查看代码下 while 1 每分钟运行多少次。在这种情况下,请尝试以下操作:
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')
请注意,删除 print(y) 将导致每分钟执行次数增加。
【解决方案2】:
不能说每分钟,但您可以使用line_profiler 模块,该模块具有每个命中表的时间