处理语言:减慢循环执行速度的方法吗?

问题描述 投票:1回答:3

我只是在学习编码,正在逐步阅读有关处理语言的第一本编码书。这是本书中的一个示例,我想对其进行更多分析:

size(480, 120);
background(0);
smooth();
noStroke();

    for (int y = 0; y <= height; y += 40) {
        for (int x = 0; x <= width; x += 40) {
          fill(255, 140);
          ellipse(x, y, 40, 40);
    }
}

我想知道是否有任何方法可以将for循环的执行速度减慢,以便我可以在执行过程中用肉眼看到?我相信,这在分析循环方面现在和将来都对我有很大帮助。

for-loop processing
3个回答
0
投票

由于draw功能以每秒30-60次的速度重绘场景,因此停止绘制窗口是有问题的。

因此,仅出于基本了解for循环就足够了:

int num = 0;

void setup() 
{
  textSize(12);
  //increased size so you can see all numbers and circles
  size(480+100, 120+100);
  background(0);
  smooth();
  noStroke();
  //stop draw function - try to delete it :)
  noLoop();  
}

void draw() { 
 //just move so I dont have to rewrite all coordinates  
 translate(50, 50);  
 //old width and height 
  for (int y = 0; y <= 120; y += 40) {
    for (int x = 0; x <= 480; x += 40) {      
      fill(255, 140);
      ellipse(x, y, 40, 40);
      text(num, x, y);
      num++;
    }
  }  
}

0
投票

您可以使用函数millis()在每次循环迭代中创建一个暂停。它返回自程序启动以来的时间(以毫秒为单位)。使用一个小while循环,您可以创建一个“空转”所需时间的循环。

编辑:看起来应该像这样:

idletime=millis()+1000;    //wait for 1 second
while(idletime>millis())
  {}

0
投票

for循环中millis()的问题在于,for循环在绘制之前会运行所有代码,因此,告诉它等待一秒钟只会在代码的第一个循环之后运行,而millis()将空闲时间要多一些,而while语句中的任何内容都不再运行

© www.soinside.com 2019 - 2024. All rights reserved.