[Python]使用timer测量代码的执行速度

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791


EX:
class Solution:
    def find(self, target: int,array:list) -> bool:
        #0
        if len(array) == 0 or target == None or array == None:
            return False
        # write code here
        lenRow = len(array)
        lenColume = len(array[0])

        indexRow = 0
        indexColume = 0
        while True:
            if array[indexRow][indexColume] < target:
                indexRow+=1
                indexColume+=1
            elif array[indexRow][indexColume] == target:
                return True
            else:
                #ij>target
                for index in range(indexRow):
                    if array[index][indexColume] == target:
                        return True
                for index in range(indexColume):
                    if array[indexRow][index] == target:
                        return True
                #no match
                return False

def main():
    import sys
    import io
    import time
    nums = [[1,3,5,7,9],[2,4,6,8,10],[11,13,15,17,19],[12,14,16,18,20],[21,23,25,27,29],[22,24,26,28,30]]
    n = 29
    start =time.perf_counter()
    ret = Solution().find(n,nums)
    end = time.perf_counter()
    print(end - start)

    print(ret)


if __name__ == '__main__':
    main()

result:

C:\Users\s00383953\PycharmProjects\Leetcode\venv\Scripts\python.exe C:/Users/s00383953/PycharmProjects/Leetcode/temp.py
1.4806000000006092e-05
True

Process finished with exit code 0

 

 
posted @ 2019-07-09 15:41  夜歌乘年少  阅读(551)  评论(0编辑  收藏  举报