Improve performance of constraint-adding in Gurobi (Python-Interface)
Question: i got this decision variable:

    
    
    x={}
    for j in range(10):
        for i in range(500000):
            x[i,j] = m.addVar(vtype=GRB.BINARY, name="x%d%d" %(i,j))
    

so i need to add constraints for each x[i,j] variable like this:

    
    
    for p in range(10):
        for u in range(500000):
            m.addConstr(x[u,p-1]<=x[u,p])
    

this is taking me so much time, more that 12hrs and then a lack of memory pop-
up appears at my computer. Can someone helpme to improve this constraint
addition problem


Answer: ## General Remark:

  * It looks quite costly to add 5 million constraints in general

## Specific Remark:

### Approach

  * You are wasting time and space by using _dictionaries_
    * Despite having constant-access complexity, these constants are big
    * They are also wasting memory 
  * In a simple 2-dimensional case like this: stick to arrays!

### Validity

  * Your indexing is missing the border-case of the first element, so indexing breaks!

Try this (much more efficient approach; using numpy's arrays):

    
    
    import numpy as np
    from gurobipy import *
    
    N = 10
    M = 500000
    
    m = Model("Testmodel")
    x = np.empty((N, M), dtype=object)
    for i in range(N):
        for j in range(M):
            x[i,j] = m.addVar(vtype=GRB.BINARY, name="x%d%d" %(i,j))
    m.update()
    
    for u in range(M):  # i switched the loop-order
        for p in range(1,N):  # i'm handling the border-case
            m.addConstr(x[p-1,u] <= x[p,u])
    

**Result:**

  * _~2 minutes_
  * _~2.5GB_ memory (complete program incl. Gurobi's internals)

