GMP's speed

Marc Glisse marc.glisse at
Fri Mar 9 10:26:02 CET 2012

On Fri, 9 Mar 2012, Chris Osborne wrote:

> I'm building my first real programs using gmp, in one of my first real 
> forays into c++ from the world of java. I built a rapid badly designed 
> proof of concept of my program in java, and have spent a few days 
> rebuild the program in a neater manner in c++ (it still isn't great 
> though). The program performs a few calculations, for some research that 
> I am performing on polynomials. Such as a user defines a max and min 
> value for x and the program then calculates d=(b+1)²-4(120b²-bx) for all 
> values of b that allow d to be positive. It then looks at floor(sqrt(d)) 
> and compares it to d, if they are the same, the the loop for checking 
> values of b is broken and x increases by 1, otherwise when it has tested 
> all of the values and if this previous statement did not apply to any of 
> them then it writes the value into a text file created on initialization 
> and moves onto the next value of x. What supprised me was that my java 
> program using doubles takes around 7s to perform this operation for 
> 0<x<100000 wheras this program in c++ using only gmp functions, because 
> we want to test much bigger numbers later, takes around 19s. After a few 
> different tests I happened to be watching processor usage as the two 
> programs executed. Java, which of course can never utilise a cpu to its 
> full potential brought the 4 cores of my cpu up to around 60-70% usage, 
> whereas the c++ just floored 1 core (so 25% of total cpu), unsurprising 
> as I didn't do any threading works.
> To get an accurate representation of the time taken by these programs 
> should I instead be looking at their cpu time as opposed to their 
> "clock" time? Or is GMP just quite slow on smaller number due to the 
> algorithms it uses being designed for very large numbers?

You didn't say much about what you were doing. Did you just replace 
"double" with "mpf_class"? Set some precision?

Of course gmp is much slower than builtin types. And it is slower by a 
factor larger than the 2-3 you mention. There must be something missing in 
your email, because I don't understand how you can expect gmp to be as 
fast as double...

> One other 
> question, which I may not be supposed to ask here, but is there any easy 
> way of making applications multi-threaded, I imagine not, but, if 
> somebody has decent resource on this area, I'd be very obliged if they'd 
> send a link, because this program is gonna need to be multi-threaded in 
> the long run.

openmp is the easiest, when it is sufficient for your needs.

Marc Glisse

More information about the gmp-discuss mailing list