import time import cppy.cp_util as util # 工具函数 def extract_words(path_to_file): return util.extract_file_words(path_to_file) def frequencies(word_list): return util.get_frequencies(word_list) def sort(word_freq): return util.sort_dict(word_freq) # 闭包 def profile(f): def profilewrapper(*arg, **kw): start_time = time.time() ret_value = f(*arg, **kw) elapsed = time.time() - start_time print(f"{f.__name__} took {elapsed} s") return ret_value return profilewrapper # 装饰 tracked_functions = [extract_words, frequencies, sort] for func in tracked_functions: globals()[func.__name__] = profile(func) # 自省 if __name__ == "__main__": word_freqs = sort( frequencies(extract_words( util.testfilepath )) ) util.print_word_freqs(word_freqs)