Is there a big performance difference between python's sum and ortools' solver.Sum?

207 views
Skip to first unread message

Li Mike

unread,
Mar 3, 2021, 10:20:05 PM3/3/21
to or-tools-discuss
Whien building constraints in a lp model, both python's sum and  solver.Sum work.
Which one is better?
If the  performance difference is not big, I would like to use sum.
Any suggestion?

blind.line

unread,
Mar 3, 2021, 11:06:48 PM3/3/21
to or-tools...@googlegroups.com
I think the python sum won’t do the right thing. You should use solver.Sum


Renames MakeSum to Sum, but it accepts a list of IntVar and does the right thing with them. Don’t be fooled by the similar naming. 

James

On Mar 3, 2021, at 19:20, Li Mike <qtb...@gmail.com> wrote:

Whien building constraints in a lp model, both python's sum and  solver.Sum work.
Which one is better?
If the  performance difference is not big, I would like to use sum.
Any suggestion?

--
You received this message because you are subscribed to the Google Groups "or-tools-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to or-tools-discu...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/or-tools-discuss/9c902540-af19-4c48-8c89-28d5b0789675n%40googlegroups.com.

blind.line

unread,
Mar 3, 2021, 11:11:09 PM3/3/21
to or-tools...@googlegroups.com
Oh ... caveat to my posted reply. I just noticed you were asking about LP model. I’ve only used routing solver and CP-SAT solvers. It might be different for LP, but I’d guess not. 


James

On Mar 3, 2021, at 19:20, Li Mike <qtb...@gmail.com> wrote:

Whien building constraints in a lp model, both python's sum and  solver.Sum work.
Which one is better?
If the  performance difference is not big, I would like to use sum.
Any suggestion?

--

Laurent Perron

unread,
Mar 4, 2021, 12:50:00 AM3/4/21
to or-tools-discuss
The sum() creates a very unbalanced syntax tree. The traversal of this tree can be expensive for large expressions (above a few thousands terms). 

Solver.Sum() creates one flat expression which can be significantly faster for these large expressions. 

Priidik Vilumaa

unread,
Mar 4, 2021, 2:40:47 AM3/4/21
to or-tools...@googlegroups.com
So we should always use solver.Sum()? Does this hold for all solvers (where applicable)?

Laurent Perron

unread,
Mar 4, 2021, 2:43:29 AM3/4/21
to or-tools-discuss
In python, 

use solver.Sum() for the routing solver and the linear solver.

The API is cp_model.LinearExpr.Sum() for CP-SAT.

It depends, if you know the size is small, use sum(). If the size is data dependent, use Sum().
Laurent Perron | Operations Research | lpe...@google.com | (33) 1 42 68 53 00



Reply all
Reply to author
Forward
0 new messages