如何在使用 CPLEX Python API 后获取经过时间的值

use*_*345 5 python cplex python-3.x

我正在使用 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)
...
Run Code Online (Sandbox Code Playgroud)

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

我对 python 和 CPLEX 非常陌生,非常感谢您的帮助。

rke*_*rsh 2

要获取总求解时间(以挂钟时间为单位),可以使用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()
Run Code Online (Sandbox Code Playgroud)

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

您可能也对get_dettime感兴趣;它的使用方式与(如上所述)相同get_time,但不受计算机负载的影响。