Go Down

Topic: How many loops in a second? (Read 609 times) previous topic - next topic

ReCreate

OK, So i have an atmega328(20 MHz I believe), How many times will
Code: [Select]

while(1)
{
//this peice of code
}

run in a second?

tep

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

ReCreate

#2
Nov 17, 2009, 01:58 am Last Edit: Nov 17, 2009, 02:10 am by ReCreate Reason: 1
Oh sweet i never knew about that function :P thanks!
Edit: So this code
Code: [Select]
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...

westfw

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

Mike Murdock

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: [Select]
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

Go Up