python - 如何在使用 CPLEX Python API 后获取耗时的值

标签 python python-3.x cplex

我正在使用 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 的新手,非常感谢任何帮助。

最佳答案

要获得总求解时间(挂钟时间),您可以使用 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(如上所述)一样使用,但不受机器负载的影响。

关于python - 如何在使用 CPLEX Python API 后获取耗时的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46832501/

相关文章:

python - Matplotlib 在第一帧后停止动画

java - 使用 ILOG Cplex Java API 生成 LP 约束

java - 如何使用 java 从 CPLEX 导出双模型?

java - 调用 IBM ILOG CPLEX 时出现 EXCEPTION_ACCESS_VIOLATION

python -c cmd 将等待所有进程完成

python - 将 Python 模块导入 AWS Lambda

Python Selenium chrome - 如何禁用用户输入

python - 随机选择元组中的值

linux - 清理 CSV(工件和缺少间距)

宇宙飞船上接收消息的系统的算法设计