【问题标题】:How would I time this function我将如何计时此功能
【发布时间】:2020-08-09 06:04:58
【问题描述】:

我想确定用于解决 Python 中的背包问题的动态编程算法的运行时间。我知道 import timeit 和 time 但不知道如何在这里实现它们。我不是一个很好的程序员!

def DPKP(v, s, C):
    # Applies the dynamic programming method to the knapsack problem where v are the
    # values of the n items, s are the sizes of the n items, and C is the capacity.
    n = len(v)
    V = [ [0 for cp in range(C+1)] for j in range (n)  ]
    X = [ [0 for cp in range(C+1)] for j in range (n)  ]

    for cp in range(C+1):
        if s[n-1] <= cp:
            V[n-1][cp] = v[n-1]
            X[n-1][cp] = 1

    for i in reversed(range(n-1)):
        for cp in range(C+1):
            if s[i] <= cp:
                if v[i] + V[i+1][cp-s[i]] > V[i+1][cp]:
                    V[i][cp] = v[i] + V[i+1][cp-s[i]]
                    X[i][cp] = 1
                else:
                    V[i][cp] = V[i+1][cp]
            else:
                V[i][cp] = V[i+1][cp]

    return V, X

【问题讨论】:

  • "我知道 import timeit 和 time 但不知道如何在这里实现它们。"你读过文档吗?

标签: python python-3.x algorithm time


【解决方案1】:

timeit 模块需要一个可调用语句,但当您是 Python 新手并尝试传递参数时,这有点难以理解。

我知道的最简单的方法是将需要参数的函数与下面的另一个函数包装起来。

def function_test():
    DPKP([1,2,3], [1,2,3], 0)

print(timeit.timeit(function_test, limit=100))

【讨论】:

    【解决方案2】:

    你可以添加下面这行代码-

    import time
    
    #at the start of the code
    time1 = time.time()
    
    #at the end of the code
    time2 = time.time()
    
    print(time2- time1)
    

    这将为您提供以秒为单位的运行时间

    【讨论】:

      【解决方案3】:

      您可以在运行函数之前和运行函数之后花时间计算差异,例如

      import time
      
      # get current time
      old = time.time()
      # run function
      DPKP(...)
      # print difference
      print("Time elapsed in seconds:", time.time() - old)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多