user2065929
user2065929

Reputation: 1095

How to add a value to a variable in a loop

I have a simple question

I am looping a section of code, the aim of this code is to collect the duration of time taken. I can do this for each time the loop is run, but what I want to do is, for example, is to collect the duration of time each time the loop is run, store these values, add them together and then average these how can I achieve this ?

Also when the loop has completed its times, it moves on and the total duration needs to be reset

this is my current code :

    if (myrank == 0) {              
        for (int len = minlen; len <= maxlen; len *= 2) { //len=*2 doubles the ping size each time
            for (int i = 0; i < MAX_LOOPS;) {
            long startTime = System.nanoTime();                  

            long endTime = System.nanoTime();
            long duration = endTime - startTime;
            durationseconds = duration; // this is where i want to store all the durations               

            i++;
        }

Thanks guys :)

Upvotes: 0

Views: 153

Answers (2)

Lavanya
Lavanya

Reputation: 319

You can have something like below :

 if (myrank == 0) {              
    for (int len = minlen; len <= maxlen; len *= 2) { 
   long durationseconds =0;
        for (int i = 0; i < MAX_LOOPS;) {
            ----
            durationseconds = durationseconds + duration;
              ---
        }

     float avgSecPerLoop = durationsseconds / MAX_LOOPS

Upvotes: 3

Stephan
Stephan

Reputation: 8090

Try this:

ArrayList<Long> durations = new ArrayList<Long>();
//start loop            
durations.add(duration);
// end loop

After you have the time for each iteration you can calculate the average or total or whatever you want

Or better (faster) yet if you know from the start how many iterations you will do you can use a primitive array to store the times

long[] durations = new long[NB_ITERATIONS];
int counter=0;
//start loop            
durations[counter++] = duration;
//end loop

Upvotes: 2

Related Questions