Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Come The Same Method Running Time Differ's At Each Time?

This might be the question that suits to all programming languages(I guess!). I have a code like this in Groovy:

def a =['asd','sdf','sdr','asd','tty','gfdg','dfgt','rfgsf','rfas','asddre','asdfr','adsrf']
start = System.currentTimeMillis() 
println a.sort()
end = System.currentTimeMillis() 
println "Sort in-built is ${end-start}"
def InsertionSort(def b = [])
{
   for(out=1;out<b.size();out++)
    {
        temp = b[out]
        in1 = out;
        while(in1>0 && b[in1-1]>=temp)
        {
            b[in1] = b[in1-1]
            --in1
        }
        b[in1] = temp;
    }
    return b
}
start = System.currentTimeMillis() 
c = InsertionSort(a)
end = System.currentTimeMillis() 
println "Insertion Sort is ${end-start}"
println c

Clearly the above code checks the running time of in-built sort function and my function named as InsertionSort which also does the same job as sort.

Now I run this same code at different time. Say when I execute the code at time 8:34:33 pm I get the output as:

[adsrf, asd, asd, asddre, asdfr, dfgt, gfdg, rfas, rfgsf, sdf, sdr, tty]
Sort in-built is 4
Instertion sort is 6
[adsrf, asd, asd, asddre, asdfr, dfgt, gfdg, rfas, rfgsf, sdf, sdr, tty]

Now at 8:35:03 when I execute the same program I get output as:

[adsrf, asd, asd, asddre, asdfr, dfgt, gfdg, rfas, rfgsf, sdf, sdr, tty]
Sort in-built is 1
Insertion Sort is 1
[adsrf, asd, asd, asddre, asdfr, dfgt, gfdg, rfas, rfgsf, sdf, sdr, tty]

After some moment of seconds I get output as:

[adsrf, asd, asd, asddre, asdfr, dfgt, gfdg, rfas, rfgsf, sdf, sdr, tty]
Sort in-built is 0
Insertion Sort is 1
[adsrf, asd, asd, asddre, asdfr, dfgt, gfdg, rfas, rfgsf, sdf, sdr, tty]

Did you notice that the running time of method changes for each execution of the program? Noticeably, the change is vary large from first execution and second execution. So does this mean Groovy caches the latest output somewhere,for some min/sec? How come this change as per second's?

Thanks in advance.

like image 411
Ant's Avatar asked Jun 04 '26 00:06

Ant's


2 Answers

Many reasons.

  1. Other background task taking up CPU time.
  2. In languages using a JVM the JVM could have JIT enabled and optimized certain runs especially if a block of code is repeatedly run without restarting the JVM.
  • Use System.nanoTime() instead of System.currentTimeMillis() as 'granularity of the value depends on the underlying operating system' and is not accurate.
  • You get different runtimes as there are many other processes competing for CPU ressources.
  • Runtime optimization by the Java VM (JIT, loop unrolling or ..)
like image 35
flob Avatar answered Jun 05 '26 13:06

flob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!