Python算法题集_检测函数用时和内存占用的模块【自搓】

    最近对算法的优化有了兴趣,陆续做了一些算法题

    做着做着,有些问题就浮现出来咯

  1. 网站上测试时用时受服务器负载情况影响,每次都不同

  2. 网站会提示免费会员不能算法提交太快

    既然如此,干脆就手搓一个自用测量函数运行用时、内存占用的代码单元CheckFuncPerf.py

    自己研究算法的时候本地进行测试,也给大家分享出来


    代码单元CheckFuncPerf.py介绍

1. 概述

名称 说明 备注
模块名称 CheckFuncPerf.py,自用时引用为cfp 内存数值会波动,建议作为定性参数不作为定量参数
版本号 V1.0.0.1 2024.1.28
下载地址 测量函数运行用时、内存占用的代码单元CheckFuncPerf.py以及使用方法 CSDN原创资源,有可能要1月29日才能审核通过哈
使用方法 import CheckFuncPerf as cfp 内存测试有单词模式和增强模式【9次取最大值】
返回参数 字典,exec_time为用时*(秒)*,mem_use为内存(KB),result为函数返回值 返回信息的函数,msg为返回信息
使用建议 建议使用返回信息函数,返回内容多一个信息

2. 测量函数用时getTimeStr返回值为字典,第二个例子为多参数函数例子

import CheckFuncPerf as cfp

# 测试函数1
def test1(icount = 10):
    a = [i for i in range(icount ** 6)]
    b = [j for j in range(icount ** 7)]
    return sum([x + y for x, y in zip(a, b)])

# 测试函数2
def test2(icount, jcount):
    a = [i for i in range(icount ** 7)]
    b = [j for j in range(jcount ** 7)]
    return sum([x + y for x, y in zip(a, b)])
    
    print(getTimeStr(test1)['msg'])
    
print(cfp.getTimeStr(test1))
# 执行结果
{'exec_time': 0.6363005638122559, 'result': 999999000000, 'msg': '函数 test1 的运行时间为 636.300564 ms'}

print(getTimeStr(test2, 8, 9)['msg'])
# 执行结果
函数 test2 的运行时间为 504.688978 ms

3. 测量函数内存占用getMemoryStrgetMemoryStrExt,返回值为字典;ext版本执行9次取最大值,用时会较长

import CheckFuncPerf as cfp

# 测试函数1
def test1(icount = 10):
    a = [i for i in range(icount ** 6)]
    b = [j for j in range(icount ** 7)]
    return sum([x + y for x, y in zip(a, b)])

# 测试函数2
def test2(icount, jcount):
    a = [i for i in range(icount ** 7)]
    b = [j for j in range(jcount ** 7)]
    return sum([x + y for x, y in zip(a, b)])
    
    print(getTimeStr(test1)['msg'])
    
print(getMemoryStr(test2, 8, 9)['msg'])
# 执行结果
函数 test2 的内存使用量为 4.00 KB

print(getMemoryStrExt(test1, 8)['msg'])
# 执行结果
函数 test1 的内存使用量为 256.00 KB

4. 同时测量函数用时和内存占用getTimeMemoryStrgetTimeMemoryStrExt,返回值为字典;ext版本执行9次取最大值,用时会较长

import CheckFuncPerf as cfp

# 测试函数1
def test1(icount = 10):
    a = [i for i in range(icount ** 6)]
    b = [j for j in range(icount ** 7)]
    return sum([x + y for x, y in zip(a, b)])

# 测试函数2
def test2(icount, jcount):
    a = [i for i in range(icount ** 7)]
    b = [j for j in range(jcount ** 7)]
    return sum([x + y for x, y in zip(a, b)])
    
    print(getTimeStr(test1)['msg'])
    
print(cfp.getTimeMemoryStr(test1, 8)['msg'])
# 执行结果
函数 test1 的运行时间为 129.58 ms;内存使用量为 256.00 KB

print(getTimeMemoryStrExt(test2, 8, 9)['msg'])
# 执行结果
函数 test2 的运行时间为 530.02 ms;内存使用量为 8.00 KB

如果大家用起来有什么不方便的,评论、私信给我发消息,尽量抽空改哈

may the odds be ever in your favor ~

你可能感兴趣的:(Python,python,测量,性能优化)