1

I am using scala, a timing function to time the method.

def timing()(f: => T) = {
  val start = System.currentTimeMillis()
  val result = f
  val end = System.currentTimeMillis()
  // print time here
  result
}

I have a fun() and use following to time it.

(0 to 10000).map{
  timing(fun())
}

it is 8ms on average

I use following and time it again

(0 to 10000).map{
  timing(fun())
  Singleton.synchronized(Singleton.i += 1)
  Thread.sleep(50)
  Singleton.synchronized(Singleton.i -= 1)
}
object Singleton{
  var i = 0
}

The timing shows fun on average becomes 30ms now. Very few records could be 8ms, and most of them are around 30~35ms

but the timing is totally outside the synchronized block. How does this happen? How does synchronization bring the overhead?

Litchy
  • 623
  • 7
  • 23
  • It's really hard to know what exactly your code does (`timing` seems to be a custom function? what does it do?). But keep in mind that synchronization involves read barriers, which can lead to memory caches effectively being invalidated and your `fun` having to re-read data from main memory that it could otherwise just grab from one of the caches. – Joachim Sauer Sep 28 '20 at 09:46
  • 5
    Also, read [how do I write a correct micro-benchmark in Java](/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java), as it contains very important information about benchmarking in general (in the absence of clear indication to the contrary, I assume that every microbenchmark posted on this site is wrong). – Joachim Sauer Sep 28 '20 at 09:49
  • 1
    That just confirmed my fears about wrong benchmarking. Please read the linked-to post. – Joachim Sauer Sep 28 '20 at 12:27
  • @JoachimSauerJ Seems this is the point, could you post an short answer? – Litchy Sep 29 '20 at 02:32

0 Answers0