Caching in python is working slower than without caching

In a Python program, I have to load a couple of thousands of files. I want to maintain their cache. I am able to create the cache using joblib. But for me, the program loads the data faster if I disable the caching.

Step to run MWE:

  • For my MWE, you can download my dummy files from Github.
  • set the paths to dummy file directory and any directory to store cache in the variables dummy_files_basepath and cache_dir

My MWE:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import os
import sys
from concurrent.futures import ThreadPoolExecutor
import joblib
def __load_file(filepath):
with open(filepath, 'r') as file:
return filepath, file.read()
def _load_files_data(basepath, filenames, enable_cache = False, cache_dir = None):
if enable_cache:
memory = joblib.Memory(cache_dir, verbose=0)
load_file_data = memory.cache(__load_file)
with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:
data = list(executor.map(lambda filename: load_file_data(os.path.join(basepath, filename)), filenames))
else:
with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:
data = list(executor.map(lambda filename: __load_file(os.path.join(basepath, filename)), filenames))
return data
class FilesLoader:
@classmethod
def load_files_data(cls, basepath, enable_cache = False, cache_dir = None):
# find the files with extension .txt
filenames = os.listdir(basepath)
filenames = [filename for filename in filenames if filename.endswith('.txt')]
# load the data using multipe threads
data = _load_files_data(basepath, filenames, enable_cache, cache_dir)
return data
####----------------------------------------Sample Run------------------------------------####
if __name__ == '__main__':
dummy_files_basepath = "SET_PATH_TO_MY_DUMMY_FILES"
cache_dir = "SET_ANY_PATH"
# record the time taken to load the data
import time
start = time.time()
data = FilesLoader.load_files_data(dummy_files_basepath, enable_cache = True, cache_dir = cache_dir)
print(f"Time taken to load the data: {time.time() - start}")
print(len(data))
print(f"First data filepath. {data[0][0]}")
</code>
<code>import os import sys from concurrent.futures import ThreadPoolExecutor import joblib def __load_file(filepath): with open(filepath, 'r') as file: return filepath, file.read() def _load_files_data(basepath, filenames, enable_cache = False, cache_dir = None): if enable_cache: memory = joblib.Memory(cache_dir, verbose=0) load_file_data = memory.cache(__load_file) with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor: data = list(executor.map(lambda filename: load_file_data(os.path.join(basepath, filename)), filenames)) else: with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor: data = list(executor.map(lambda filename: __load_file(os.path.join(basepath, filename)), filenames)) return data class FilesLoader: @classmethod def load_files_data(cls, basepath, enable_cache = False, cache_dir = None): # find the files with extension .txt filenames = os.listdir(basepath) filenames = [filename for filename in filenames if filename.endswith('.txt')] # load the data using multipe threads data = _load_files_data(basepath, filenames, enable_cache, cache_dir) return data ####----------------------------------------Sample Run------------------------------------#### if __name__ == '__main__': dummy_files_basepath = "SET_PATH_TO_MY_DUMMY_FILES" cache_dir = "SET_ANY_PATH" # record the time taken to load the data import time start = time.time() data = FilesLoader.load_files_data(dummy_files_basepath, enable_cache = True, cache_dir = cache_dir) print(f"Time taken to load the data: {time.time() - start}") print(len(data)) print(f"First data filepath. {data[0][0]}") </code>
import os
import sys
from concurrent.futures import ThreadPoolExecutor
import joblib

def __load_file(filepath):
        with open(filepath, 'r') as file:
                return filepath, file.read()
    
def _load_files_data(basepath, filenames, enable_cache = False, cache_dir = None):
    if enable_cache:
        memory = joblib.Memory(cache_dir, verbose=0)
        load_file_data = memory.cache(__load_file)
        with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:
            data = list(executor.map(lambda filename: load_file_data(os.path.join(basepath, filename)), filenames))
    else:
        with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor:
            data = list(executor.map(lambda filename: __load_file(os.path.join(basepath, filename)), filenames))

    return data    

class FilesLoader:    
    @classmethod
    def load_files_data(cls, basepath, enable_cache = False, cache_dir = None):
        # find the files with extension .txt
        filenames = os.listdir(basepath)
        filenames = [filename for filename in filenames if filename.endswith('.txt')]

        # load the data using multipe threads
        data = _load_files_data(basepath, filenames, enable_cache, cache_dir)            

        return data

####----------------------------------------Sample Run------------------------------------####
if __name__ == '__main__':
    dummy_files_basepath = "SET_PATH_TO_MY_DUMMY_FILES"  
    cache_dir = "SET_ANY_PATH"

    # record the time taken to load the data
    import time
    start = time.time()
    data = FilesLoader.load_files_data(dummy_files_basepath, enable_cache = True, cache_dir = cache_dir)
    print(f"Time taken to load the data: {time.time() - start}")
    print(len(data))
    print(f"First data filepath. {data[0][0]}")

Question: Why accessing data is slower with caching enabled? In this example, I am loading .txt file but in my actual program I have .pkl files

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật