Go Down

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


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

//this peice of code

run in a second?


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


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()
void loop()
 while(millis()<=1000)//we loop over
   loops = loops + 1;//increments it
 Serial.print("Time taken: ");
 Serial.print("Loops: ");
 delay(1000);//wait a second

Send me(via serial)

Time taken: 1011
Loops: -28425

why is it a negative number?

Edit2: Changed it to an unsigned long, and sent
Time taken: 12375
Loops: 338769

Thanks anyways...


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:



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.



Go Up