刷算法题,想比较下不同解法的性能,找到了这个pycharm工具 # Optimize your code using profilers
详细来讲,有2个函数rob1、rob2,实现同样的功能:
| 函数 | 时间复杂度 | 空间复杂度 |
|---|---|---|
| rob1 | O(n) | O(n) |
| rob2 | O(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)
来看下profile结果
其中:
| Item | Description |
|---|---|
| Saves the profiling results in the .pstat file for cProfile profiler and the .prof file for vmprof. | |
| Stops the profiler. | |
| Closes the profiler tab. |
显然rob2函数的数据更优(总时间、单独调用时间 明显更少)
统计数据面板Statistics:
| Item | Description |
|---|---|
| Name | The name of the function. |
| Call Count | Number of calls of the chosen function. |
| Time | Execution 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 Time | Own 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. |
调用流程图:
直接由模块test.py调用函数rob1、rob2