Average time to traverse a directory

import matplotlib.pyplot as plt from pathlib import Path from os import path, listdir, scandir, walk from time import perf_counter times = {} colors = ['c6acc7', 'ecb4bf', 'fbd7b7', 'fdf3b8'] versions = ['pathlib', 'listdir', 'scandir', 'walk'] bar_width, bar_gap = 40, 10 barx = bar_width + bar_gap font_size = 11 text_below_spacing = -0.025 top_dir = '101_ObjectCategories' iterations = 20 def pathlib_v1(): p = Path(top_dir) for pdir in p.iterdir(): p = Path(pdir) for f in p.iterdir(): print(f) def listdir_v2(): for f in listdir(top_dir): for f in listdir(path.join(top_dir, f)): print(f) def scandir_v3(): for f in scandir(top_dir): for f in scandir(path.join(top_dir, f.name)): print(f.name) def walk_v4(): for directory, _, files in walk(top_dir): for f in files: print(f) for k, version in enumerate(versions): s = perf_counter() for i in range(iterations): # Bad practice, but handy eval( '{0}_v{1}()'.format(version, k+1) ) e = perf_counter() times[version] = (e-s) / iterations fig, ax = plt.subplots() for k , (version, time) in enumerate(times.items()): print(': '.join([version, str(time)])) k50 = k * barx ax.bar(k50, time, bar_width, color='#'+colors[k]) ax.text(k50, text_below_spacing, version, ha='center', va='center', fontsize=font_size) ax.set_xticklabels([]) ax.set_title('Average time to traverse a directory') ax.set_ylabel('Time (s)') plt.tight_layout() plt.show() """ pathlib: 0.7946676499035675 scandir: 0.3221788138500415 walk: 0.3180693927512038 listdir: 0.29686591199715623 """ Average time to traverse a directory by different methods in Python