【问题标题】:how to get value of elapsed time after using CPLEX Python API使用 CPLEX Python API 后如何获取经过时间的值
【发布时间】:2018-03-31 15:29:23
【问题描述】:

我正在使用 CPLEX python API 来解决优化问题。该模型被命名为 DOT。当我运行 DOT.solve() 时,python 控制台中会出现很多信息:

Iteration log ...
...
Network - Optimal:  Objective =    1.6997945303e+01
Network time = 0.48 sec. (91.93 ticks)  Iterations = 50424 (8674)
...

我的问题是,是否有一种简单的方法可以获取经过时间的值(即,在我的情况下为 0.48)?不仅适用于网络优化器,还适用于对偶方法、屏障方法。

我是 python 和 CPLEX 的新手,非常感谢任何帮助。

【问题讨论】:

    标签: python python-3.x cplex


    【解决方案1】:

    要获得总求解时间(以挂钟时间计),您可以使用get_time 方法。要获取日志输出中显示的“网络时间”的值,您必须解析日志输出。下面是一个演示这两者的示例:

    from __future__ import print_function
    import sys
    import cplex
    
    
    class OutputProcessor(object):
        """File-like object that processes CPLEX output."""
    
        def __init__(self):
            self.network_time = None
    
        def write(self, line):
            if line.find("Network time =") >= 0:
                tokens = line.split()
                try:
                    # Expecting the time to be the fourth token. E.g.,
                    # "Network", "time", "=", "0.48", "sec.", ...
                    self.network_time = float(tokens[3])
                except ValueError:
                    print("WARNING: Failed to parse network time!")
            print(line, end='')
    
        def flush(self):
            sys.stdout.flush()
    
    
    def main():
        c = cplex.Cplex()
        outproc = OutputProcessor()
        # Intercept the results stream with our output processor.
        c.set_results_stream(outproc)
        # Read in a model file (required command line argument). This is
        # purely an example, thus no error handling.
        c.read(sys.argv[1])
        c.parameters.lpmethod.set(c.parameters.lpmethod.values.network)
        start_time = c.get_time()
        c.solve()
        end_time = c.get_time()
        print("Total solve time (sec.):", end_time - start_time)
        print("Network time (sec.):", outproc.network_time)
    
    
    if __name__ == "__main__":
        main()
    

    这应该让您了解如何从日志中解析出其他信息(这并不是一个复杂解析器的示例)。

    您也可能对get_dettime 感兴趣;它可以像get_time 一样使用(如上),但不受机器负载的影响。

    【讨论】:

    • 我根据您的回答修改了我的代码,它成功了,谢谢!但是我还有一个问题:总时间似乎比网络时间长得多(例如1.72s对0.56s),这是为什么(在“总时间”期间和“网络时间”期间它在做什么? )
    • Python API 是可调用 C 库的包装器。当您在 Python API 中调用 solve 时,会有额外的代码确定要调用哪个优化例程(例如,CPXXmipoptCPXXlpopt 等),当优化完成时,它会检查状态代码确保没有发生错误等。这种额外的处理可能就是您看到的差异。 “网络时间”是 Callable C 库本身报告的时间。您报告的差异比我所看到的要大,但是在不了解您的模型/程序的情况下,我真的无话可说。
    • 现在我有了一个草图的想法。谢谢。
    猜你喜欢
    • 2019-01-26
    • 2023-04-05
    • 2017-07-16
    • 2016-10-13
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多