Go Down

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

#### ReCreate

##### Nov 17, 2009, 01:50 am
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

#1
##### Nov 17, 2009, 01:55 am
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 amLast Edit: Nov 17, 2009, 02:10 am by ReCreate Reason: 1
Oh sweet i never knew about that function thanks!
Edit: So this code
Code: [Select]
`unsigned long time_counted = 0;//the time variableint 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

#3
##### Nov 17, 2009, 09:09 am
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

#### mfm9

#4
##### Nov 17, 2009, 03:16 pm
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 nowwhile (millis() <= end_time)...`

You may see a few more loops that way.

Regards,

-Mike

Go Up