代码性能分析-profile工具

86 阅读1分钟

刷算法题,想比较下不同解法的性能,找到了这个pycharm工具 # Optimize your code using profilers

详细来讲,有2个函数rob1、rob2,实现同样的功能:

函数时间复杂度空间复杂度
rob1O(n)O(n)
rob2O(n)O(1)
class Solution:
    def rob1(self, nums) -> int:
        n = len(nums)
        if n == 0:
            return 0
        if n == 1:
            return nums[0]
        dp = [0]*n
        dp[0],dp[1] = nums[0], max(nums[0], nums[1])
        for i in range(2, n):
            dp[i] = max(dp[i-2]+nums[i], dp[i-1])
        return dp[-1]

    def rob2(self, nums) -> int:
        n = len(nums)
        if n == 0:
            return 0
        if n == 1:
            return nums[0]
        x, y = nums[0], max(nums[0], nums[1])
        for i in range(2, n):
            x, y = y, max(x + nums[i], y)
        return y
        

if __name__ == '__main__':
    nums = [i for i in range(1000000)]
    obj = Solution()
    obj.rob1(nums)
    obj.rob2(nums)

image.png

来看下profile结果 image.png 其中:

ItemDescription
Profiling resultsSaves the profiling results in the .pstat file for cProfile profiler and the .prof file for vmprof.
Stop profilingStops the profiler.
CloseCloses the profiler tab.

显然rob2函数的数据更优(总时间、单独调用时间 明显更少)

统计数据面板Statistics:

ItemDescription
NameThe name of the function.
Call CountNumber of calls of the chosen function.
TimeExecution time of the chosen function plus all time taken by functions called by this function. The percentage of time spent in this call related to time spent in all calls in the parentheses.
Own TimeOwn execution time of the chosen function. The percentage of own time spent in this call related to overall time spent in this call in the parentheses.

调用流程图:

image.png

直接由模块test.py调用函数rob1、rob2