How to make rendering on screen faster?

edited November 2017 in Questions about Code

I am writing this program to plot graphs on screen. However, the rendering is too slow. Any clues how it can be made faster? Here is the code below. It plots a simple Archimedes spiral.

float r=0,a=0,t=0,x0=0,y0=0,x=0,y=0;
int c=80;

void setup(){
  size(1024,768);
  background(0);
  strokeWeight(1);
  stroke(c,100,150);
}

void draw(){

  translate(width/2,height/2);

   if(t<=30*PI)
    {
      x0=r*cos(a);
      y0=r*sin(a);

      a=t;//360*(sin(t/20)+0.5*sin(t/40));
      r=a;//200*(sin(t/40)+0.5*sin(t/80));

      x=r*cos(a);
      y=r*sin(a);

      line(x0,-y0,x,-y);

      t+=0.1;
   }
}

Answers

  • edited November 2017
    • Prefer renderer FX2D over the default JAVA2D for size().
    • Cache calculations in local variables.
    • For example, you calculate these 2 expressions 2x in the same block: r*cos(a) & r*sin(a).
    • I did a refactor on your code. Take a look here: :P
      https://OpenProcessing.org/sketch/475427

    /** 
     * Archimedes Spiral (v1.0.1)
     * Mproc (2017/Nov/15)
     * mod GoToLoop
     *
     * Forum.Processing.org/two/discussion/25020/
     * how-to-make-rendering-on-screen-faster#Item_1
     *
     * OpenProcessing.org/sketch/475427
     */
    
    static final boolean JAVA = 1/2 != 1/2.;
    static final String RENDER = JAVA? FX2D : JAVA2D;
    
    static final float FPS = 4*60, BOLD = 1.5;
    static final float MAX_PI = 60*PI, STEP = .1;
    
    static final color STROKE = #506496;
    
    float x0, y0;
    int cx, cy;
    
    void setup() {
      size(500, 400, RENDER);
      smooth(3);
      frameRate(FPS);
    
      strokeCap(ROUND);
      strokeWeight(BOLD);
      stroke(STROKE);
      background(0);
    
      cx = width>>1;
      cy = height>>1;
    }
    
    void draw() {
      translate(cx, cy);
    
      final float t = STEP * frameCount;
      if (t >= MAX_PI)  noLoop();
    
      final float x = t*cos(t), y = -t*sin(t);
      line(x0, y0, x0 = x, y0 = y);
    
      if (!JAVA)  return;
    
      final String s = "Ang: " + nf(t, 3, 2) +
        "  -  FPS: " + nf(frameRate, 3, 2);
    
      surface.setTitle(s);
    }
    
  • none of the above matters because you are drawing 30 * PI / .1 things at 60 frames per second, so it'll always take 940 frames, 15 seconds. as long as your draw() completes in 1/60th of a second, which it will, the code can be as sub-optimal as you like.

    in short, change the framerate

  • edited November 2017 Answer ✓

    @GotoLoop That indeed works faster on my lappy, Thanks! Although not very smooth; it's working in pieces completing portions of the curve and then displaying them on screen. Thanks, will study your code now. It's all new to me!

Sign In or Register to comment.