一.程序分析
1.使用Python语言进行编译,求数组中的最大子数组之和
#用来获得最大子数组之和定义成方法也方便后面的单元测试 def max(a): out=temp=0 for i in range(0,len(a)): temp+=a[i] if temp>out: out=temp if temp<0: temp=0 return outif name == ‘main‘:
i=1
#循环这个程序,方便封包之后更好的使用
while i == 1:
print(‘1.计算最大子数组之和‘)
print(‘2.退出‘)
print(‘输入你的选择:‘)
s=int(input())
if s == 1:
a = map(int,input(‘输入用空格隔开:‘).split())
print(‘最大的子数组之和为‘,end=‘‘)
print(max(list(a)))
elif s == 2:
i=-1
else :
print(‘请重新输入选择:‘)
s=int(input())
#使用cmd命令符进行封包 #使用封包提前pip install pyinstaller -i https://pypi.tuna.tsinghua.edu.cn/simple pyinstaller -F py文件路径 --distpath=exe文件生成路径
二.单元测试
我选择的是python单元测试unittest框架,因为程序源码中为了方便使用添加了循环然后封包,所以这里的单元测试只对我们定义的函数进行验证即可。
demo.py
class max_out(object): def __init__(self,a): self.a=a def max(a): out=temp=0 for i in range(0,len(a)): temp+=a[i] if temp>out: out=temp if temp<0: temp=0 return out
test_demo.py
import unittest from demo import *class TestDemo(unittest.TestCase):
def test_out_1(self):
a = [1,-2,3,-4,5]
self.assertEqual(max(a),5)
def test_out_2(self):
a = [-32,-10,33,-23,32,-12,41,-12,1,3,5,-98,70,-21,10,-9,61]
self.assertNotEqual(max(a),71)if name == ‘main‘:
unittest.main()
运行结果截图:
从运行结果截图来看,我们程序是正确的。
三.性能分析
选用的是cProfile模块运用cmd命令符运行代码,cProfile:基于lsprof的用C语言实现的扩展应用,运行开销比较合理。
ncalls:表示函数调用的次数;
tottime:表示指定函数的总的运行时间,除掉函数中调用子函数的运行时间;
percall:(第一个percall)等于 tottime/ncalls;
cumtime:表示该函数及其所有子函数的调用运行的时间,即函数开始调用到返回的时间;
percall:(第二个percall)即函数运行一次的平均时间,等于 cumtime/ncalls;
filename:lineno(function):每个函数调用的具体信息;
得出的结果截图:
有关对于python的程序性能分析
出处原文:https://www.cnblogs.com/wenyan1123/p/14524388.html