如何在 numba.jit 函数中测量时间?

How to measure time in numba.jit function?

我想将 conventional loop 转换为 numba.jit 函数并在内部测量其进程的时间。我尝试使用 time 模块,但它似乎与 numba 不兼容。

代码:

from numba import jit, jitclass
import time

@jit(nopython=True)
def harmonic_load_flow_func():
    time1 = time.perf_counter()
    calc = 0
    for x in range(1000000):
        calc += x
    print('time: {}'.format(time.perf_counter() - time1))

if __name__ == '__main__':
    for count in range(10):
        harmonic_load_flow_func()

输出:

C:\Users\Artur\Anaconda\python.exe C:/Users/Artur/Desktop/RL_framework/help_functions/test.py
Traceback (most recent call last):
  File "C:/Users/Artur/Desktop/RL_framework/help_functions/test.py", line 14, in <module>
    harmonic_load_flow_func()
  File "C:\Users\Artur\Anaconda\lib\site-packages\numba\core\dispatcher.py", line 401, in _compile_for_args
    error_rewrite(e, 'typing')
  File "C:\Users\Artur\Anaconda\lib\site-packages\numba\core\dispatcher.py", line 344, in error_rewrite
    reraise(type(e), e, None)
  File "C:\Users\Artur\Anaconda\lib\site-packages\numba\core\utils.py", line 80, in reraise
    raise value.with_traceback(tb)
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Unknown attribute 'perf_counter' of type Module(<module 'time' (built-in)>)

File "test.py", line 6:
def harmonic_load_flow_func():
    time1 = time.perf_counter()
    ^

[1] During: typing of get attribute at C:/Users/Artur/Desktop/RL_framework/help_functions/test.py (6)

File "test.py", line 6:
def harmonic_load_flow_func():
    time1 = time.perf_counter()
    ^


Process finished with exit code 1

是的,不支持时间模块

您可以使用 objmode() 或使用普通 python 函数包装整个调用并测量:

from numba import jit, objmode
import time

@jit(nopython=True)
def harmonic_load_flow_func_time_inside():
    with objmode(time1='f8'):
        time1 = time.perf_counter()
    calc = 0
    for x in range(1000000):
        calc += x
    with objmode():
        print('time: {}'.format(time.perf_counter() - time1))

@jit(nopython=True)
def harmonic_load_flow_func():
    calc = 0
    for x in range(1000000):
        calc += x

def main_time_inside():
    for _ in range(10):
        harmonic_load_flow_func_time_inside()

def main_time_outside():   
    for _ in range(10):
        time1 = time.perf_counter()
        harmonic_load_flow_func()
        print('time: {}'.format(time.perf_counter() - time1))

if __name__ == '__main__':
    print("measuring time inside the function")
    main_time_inside()
    print("measuring time from outside")
    main_time_outside()