Pages: [1]   Go Down
Author Topic: How many loops in a second?  (Read 510 times)
0 Members and 1 Guest are viewing this topic.
From:0x000000
Offline Offline
Full Member
***
Karma: 0
Posts: 213
sudo make me a (bread+ham+lettuce+cheese+bread)
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

OK, So i have an atmega328(20 MHz I believe), How many times will
Code:
while(1)
{
//this peice of code
}
run in a second?
Logged

France
Offline Offline
Sr. Member
****
Karma: 0
Posts: 262
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

It depends on your code!
To know it, use millis() to loop during a second and count how many times the loop was executed smiley-wink
Logged

From:0x000000
Offline Offline
Full Member
***
Karma: 0
Posts: 213
sudo make me a (bread+ham+lettuce+cheese+bread)
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Oh sweet i never knew about that function smiley-razz thanks!
Edit: So this code
Code:
unsigned long time_counted = 0;//the time variable
int loops = 0;

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  while(millis()<=1000)//we loop over
  {
    loops = loops + 1;//increments it
  }
  
  Serial.print("Time taken: ");
  Serial.println(millis());
  
  Serial.print("Loops: ");
  Serial.println(loops);  
  
  delay(1000);//wait a second
}
Send me(via serial)
Quote
Time taken: 1011
Loops: -28425
why is it a negative number?

Edit2: Changed it to an unsigned long, and sent
Quote
Time taken: 12375
Loops: 338769
Thanks anyways...
« Last Edit: November 16, 2009, 08:10:21 pm by ReCreate » Logged

SF Bay Area (USA)
Offline Offline
Tesla Member
***
Karma: 106
Posts: 6371
Strongly opinionated, but not official!
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

The overhead of a "while (1)" loop is a single 2-cycle (ok, sometimes 3 cycles) machine instruction, so it takes less than 250 ns.  There have been other discussions on optimization and speed.  See in particular:
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1230286016
Logged

Huntsville, Alabama, USA
Offline Offline
Sr. Member
****
Karma: 2
Posts: 327
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

ReCreate,

When you say 'millis() <= 1000', you are looping for less than one second.  You are saying, "loop until one second since millis() started counting has passed."  Since the millis() starts counting before setup() is called, you are getting a short count.

Try this:
Code:
unsigned long end_time;

end_time = millis() + 1000;    // one second from now
while (millis() <= end_time)
...

You may see a few more loops that way.

Regards,

-Mike
Logged

Pages: [1]   Go Up
Jump to: