PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 1, 2022

[FIXED] Which one is faster x+=x or x*=2

 November 01, 2022     performance, rust     No comments   

Issue

I recently make a program to make an image of the Mandelbrot set. To do this is I have written a function which returns if a point is a point of Mandelbrot set. And in this function I found 2 ways to do my calculation:

let temp=a;
a=a*a-b*b+x;
b=2.0*b*temp+y;

or

let temp=a;
a=a*a-b*b+x;
b*=temp;
b+=b+y;

Which one is faster if there is a faster one? (I use rust language if this changes something)?


Solution

I've put both your codes into the playground, as a public functions (assuming that your values are all floats, but this shouldn't make any real diference):

pub fn mult(mut a: f32, mut b: f32, x: f32, y: f32) -> f32 {
    let temp = a;
    a = a * a - b * b + x;
    b = 2.0 * b * temp + y;
    b
}

pub fn add(mut a: f32, mut b: f32, x: f32, y: f32) -> f32 {
    let temp = a;
    a = a * a - b * b + x;
    b *= temp;
    b += b + y;
    b
}

The assembly generated in release mode is almost identical (just reordered):

playground::mult:
    addss   xmm1, xmm1
    mulss   xmm0, xmm1
    addss   xmm0, xmm3
    ret

playground::add:
    mulss   xmm0, xmm1
    addss   xmm3, xmm0
    addss   xmm0, xmm3
    ret

So, there should be no measurable difference. However, if you're worried, you should benchmark your real case to see whether some of these approaches leads to missing optimizations in the larger picture.



Answered By - Cerberus
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing