프로그래밍

[Python] 시간이 오래 걸리는 함수 결과 파일에 저장하기 (cache)

Folivora 2020. 2. 14. 10:40
    a,b,c = get_cached_result("20200214-781199f1", lambda: sim_queue_length(sim_params))

시간이 오래 걸리는 함수의 결과를 파일에 저장하기 위한 도움 함수(helper function)를 간단하게 만들어봤다. 참고로 메모리에 caching 할 때는 functools 모듈의 lru_cache 같은 것들을 쓰면 좋다. (https://docs.python.org/3/library/functools.html

 

캐시 파일에 이미 실행 결과가 있으면 그대로 불러오고, 없으면 func를 실행한 다음, 캐시 파일에 쓴다.

def get_cached_result(cache_name, func):
    cache_file = "{}.pickle".format(cache_name)
    cache_obj = None
    if os.path.isfile(cache_file):
        with open(cache_file, "rb") as f_in:
            cache_obj = pickle.load(f_in)
    else:
        cache_obj = func()
        if not os.path.exists(cache_file):
            with open(cache_file, "wb") as f_out:
                pickle.dump(cache_obj, f_out)
    return cache_obj

사용법은 function object를 정의해서 그 자체를 넘겨준다. [함수 호출 연산 ()을 붙이지 않음]

def run_781199f1(): return sim_queue_length(sim_params)
a, b, c = get_cached_result("20200214-781199f1", run_781199f1)

혹은 익명함수를 사용할 수 있다.

a, b, c = get_cached_result("20200214-781199f1", lambda: sim_queue_length(sim_params))

(5/26/2022)

큰 차이는 없는 것 같지만, get_cached_result(cache_name, func, *args, **kwargs) 으로 정의하고 함수 호출 부분을 func(*args, **kwargs) 로 할 수도 있다. 조금 더 첨언하자면 func가 pure function일 것, 입력 파라미터가 달라지지 않을 것을 unique한 cache_name이 보장해줘야하는 단점이 존재한다. https://joblib.readthedocs.io/en/latest/memory.html 와 같은 좋은 라이브러리도 있다. :)