Try our new documentation site (beta).


Example: callback

The final example we consider is callback, which demonstrates the use of Gurobi callbacks. Callbacks are used to report on the progress of the optimization or to modify the behavior of the Gurobi solver. To use a callback, the user writes a routine that implements the desired behavior. The routine is passed to the Gurobi Optimizer when optimization begins, and the routine is called regularly during the optimization process. One argument of the user routine is a where value, which indicates from where in the optimization process the callback is invoked. The user callback routine can call the optimization library to query certain values. We refer the reader to the callback section of the Gurobi Reference Manual for more precise details.

Our callback example implements a simple termination scheme: the user passes a node count into the callback, and the callback asks the optimizer to terminate when that node count is reached. This is implemented in C as follows:

  GRBcbget(cbdata, where, GRB_CB_MIP_NODCNT, &nodecnt);
  if (nodecnt > limit)
In Python, this is implemented as:
  nodecnt = model.cbGet(GRB.Callback.MIP_NODCNT)
  if nodecnt > model._mynodelimit:
To obtain the current node count, the user routine calls the cbget routine (the GRBcbget function in C, or the cbGet method on the model object in C++, C#, Java, and Python).

Our callback example also prints progress information. In C:

  GRBcbget(cbdata, where, GRB_CB_MIP_NODCNT, &nodecnt);
  if (nodecnt - mydata->lastmsg >= 100) {
    printf("%7.0f ...", nodecnt, ...);
In Python:
  nodecnt = model.cbGet(GRB.Callback.MIP_NODCNT)
  if nodecnt % 100 == 0:
    print(int(nodecnt), "...")
Again, the user callback calls the cbGet routine to query the state of the optimization.

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.