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

2024-01-07

我正在使用 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 https://www.ibm.com/support/knowledgecenter/SSSA5P_12.7.1/ilog.odms.cplex.help/refpythoncplex/html/cplex.Cplex-class.html#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()

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

您可能感兴趣获取时间 https://www.ibm.com/support/knowledgecenter/SSSA5P_12.7.1/ilog.odms.cplex.help/refpythoncplex/html/cplex.Cplex-class.html?view=kc#get_dettime以及;它的使用方式与get_time(如上所述),但不易受到机器负载的影响。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐