Memory filter

Sungchul Kim·2021년 12월 28일
0

Issues

목록 보기
2/2
post-thumbnail

Memory usage/Computing cost가 많아져 OOM issue가 발생하는 경우가 종종 존재합니다. 오늘은 memory usage와 관련하여 간단한 라이브러리 하나를 소개하도록 하겠습니다.

Memory profiler library document를 참고하시면 좋을 거 같습니다. Memory profiler이란, line by line으로 코드의 memory의 usage를 확인할 수 있는 library입니다.

앞서 말씀드린 Memory profiler library install을 먼저 진행해 보도록 하겠습니다.

command는 아래와 같이 입력해 주시면 됩니다. conda를 사용하시면, 2번째 command를 입력하시면 됩니다!

$ pip install -U memory_profiler 

$ conda install memory_profiler 

Memory profiler library를 install하셨다면, 어떠한 기능을 수행하는지 설명하도록 하겠습니다. terminal 혹은 visual studio code 에서 command를 입력하시면 됩니다. command는 아래와 같습니다.

Memory profiler library를 호출 하거나, 첫번째 line처럼 command로 호출 해도 됩니다.

$ python3 -m memory_profiler filename.py
 
$ python3 filename.py

$ python3 -m memory_profiler filename.py
 
$ python3 filename.py

Example

from memory_profiler import profile

@profile
def my_func():
    li=[]
    for i in range(100):
        for j in range(10000):
            li.append(j)
    return li 

@profile 
def my_func2(): 
    li = [j for i in range(100) for j in range(10000)]
    return li 


if __name__ == '__main__':
    my_func()
    my_func2()

간단하게 이중 for문을 사용하여 각 line의 memory usage를 profiling 해보았습니다.

위의 table을 보시게 되면 line 923, line 928에서 memory가 증가했다는 사실을 알 수 있습니다. 이처럼 Memory profiler를 사용하게 되면 어떤 line에서 memory를 많이 사용하였는가 확인 가능합니다.

Conclusions

추가로 mprof library를 사용하면 시간에 따른 memory usage를 visualization할 수 있습니다. (mprof는 따로 다루지 않겠습니다.)

추가로 wandb.ai/comet.ml과 같은 visualization tool을 이용하여 memory usage를 확인할 수 있습니다.

profile
김성철

0개의 댓글