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?