[Spice-devel] [PATCH spice-gtk] main: Avoid sqrt in monitor compare

Frediano Ziglio fziglio at redhat.com
Fri Feb 24 13:16:17 UTC 2017


> 
> qsort cares about the sign of the difference and that should stay
> the same
> ---
>  src/channel-main.c | 5 ++---
>  1 file changed, 2 insertions(+), 3 deletions(-)
> 
> diff --git a/src/channel-main.c b/src/channel-main.c
> index cd3dee7..50c29f2 100644
> --- a/src/channel-main.c
> +++ b/src/channel-main.c
> @@ -17,7 +17,6 @@
>  */
>  #include "config.h"
>  
> -#include <math.h>
>  #include <spice/vd_agent.h>
>  #include <glib/gstdio.h>
>  #include <glib/gi18n-lib.h>
> @@ -1029,8 +1028,8 @@ static int monitors_cmp(const void *p1, const void *p2,
> gpointer user_data)
>  {
>      const VDAgentMonConfig *m1 = p1;
>      const VDAgentMonConfig *m2 = p2;
> -    double d1 = sqrt(m1->x * m1->x + m1->y * m1->y);
> -    double d2 = sqrt(m2->x * m2->x + m2->y * m2->y);
> +    double d1 = m1->x * m1->x + m1->y * m1->y;
> +    double d2 = m2->x * m2->x + m2->y * m2->y;

There's no reason to convert to double now.
All computations are done using int32_t so if you have (or had)
an overflow inside the results is (was) truncated anyway.
Unless of course you want to avoid the possible overflows but
in this case you have to convert to double before the multiplications
and also the range of resulting doubles won't fit into an int.

Overflows expected if x or y >= 32k.

>      int diff = d1 - d2;
>  
>      return diff == 0 ? (char*)p1 - (char*)p2 : diff;

Frediano


More information about the Spice-devel mailing list