Where is the problem?
val startTime = System.nanoTime timeConsumingOperations() val endTime = System.nanoTime println("Operations took " + (endTime - startTime) + " nano seconds")This is most basic approach that can be used in the simplest cases. But what if we want to measure times of multiple different operations? This simple solution would become a little complex and harder to maintain, ie.
val startTime = System.nanoTime operation1() val middleTime1 = System.nanoTime operation2() val middleTime2 = System.nanoTime operation3() val endTime = System.nanoTime println("Operation1 took " + (middleTime1 - startTime) + " ns") println("Operation2 took " + (middleTime2 - middleTime1) + " ns") println("Operation3 took " + (endTime - middleTime2) + " ns")That code is becoming hard to read, maintain and, in my opinion the worst, it almost hides our business code.
Now let's compilcate it even more by assuming that we need to run those operations multiple times (ie. in a for loop) and we need to measure their entire time of execution. We could try to do something like that:
var operation1Duration = 0L var operation2Duration = 0L var operation3Duration = 0L for(i <- 1 to 10) { val startTime = System.nanoTime operation1() val middleTime1 = System.nanoTime operation2() val middleTime2 = System.nanoTime operation3() val endTime = System.nanoTime operation1Duration += middleTime1 - startTime operation2Duration += middleTime2 - middleTime1 operation3Duration += endTime - middleTime2 } println("Operation1 took " + operation1Duration + " ns") println("Operation2 took " + operation2Duration + " ns") println("Operation3 took " + operation3Duration + " ns")And that is an ugly piece of code.
Solution Proposal
I propose a simple solution to that problem, a simple stopwatch. With this stopwatch we can refactor our third case into this:clearStopwatchResults() for(i <- 1 to 10) { stopwatch("First operation") { operation1() } stopwatch("Second operation") { operation2() } stopwatch("Third operation") { operation3() } } println(stopwatchResults)And the result of this measurement would be something like this:
Third operation -> 48 ms 355 us 124 ns First operation -> 136 ms 219 us 210 ns Second operation -> 644 ms 69 us 657 nsBasic idea for that approach is to create a Stopwatch that can measure execution time of a block of code and store it under given identifier (ie. "First operation"). It will accumulate a time of execution for given identifier, and in the end it will write out the measurement results in a readable format.
Solution Implementation
So here is the implementation of my Stopwatch:import collection.mutable import scala.StringBuilder class Stopwatch { private val measurements = mutable.HashMap[Any, Long]() def clearResults() { measurements.clear() } def apply(identifier:Any)(codeBlock: => Unit) { val start = System.nanoTime codeBlock val end = System.nanoTime val oldValue = measurements.getOrElse(identifier, 0L) measurements += identifier -> (oldValue + end - start) } def results():String = { ResultsFormatter.format(measurements) } }And there is also a companion object to provide default Stopwatch and convenient methods to use it.
object Stopwatch { private val defaultStopwatch = new Stopwatch def stopwatch(identifier:Any)(codeBlock: => Unit) { defaultStopwatch(identifier)(codeBlock) } def stopwatchResults() = defaultStopwatch.results() def clearStopwatchResults() { defaultStopwatch.clearResults() } }To complete the solution we also need a class to format our measurements results into well formatted String:
object ResultsFormatter { def format(measurements: mutable.HashMap[Any, Long]):String = { val sb = new StringBuilder measurements.foreach(appendResult(sb)) sb.toString() } private def appendResult(sb: StringBuilder)(result: (Any, Long)) { val identifier = result._1 val value = result._2 sb.append(identifier).append(" -> ") appendIfNotZero(sb, extractSeconds(value), "s") appendIfNotZero(sb, extractMills(value), "ms") appendIfNotZero(sb, extractMicro(value), "us") appendIfNotZero(sb, extractNano(value), "ns") sb.append('\n') } private def extractNano(value: Long): Long = value % 1000 private def extractMicro(value: Long) = (value / 1000) % 1000 private def extractMills(value: Long) = (value / 1000000) % 1000 private def extractSeconds(value: Long) = value / 1000000000 private def appendIfNotZero(sb:StringBuilder, value:Long, suffix:String) { if (value > 0) { sb.append(value).append(" ").append(suffix).append(" ") } } }I have to mention that this is not thread safe implementation and one instance of Stopwatch should be use within single thread.
Implementation description
Stopwatch class
The main point of the implementation is a Map called measurements. It is a mutable HashMap, for higher performance and it is used to map identifier into execution duration.
The Stopwatch class provides three public methods:
- apply(identifier:Any)(codeBlock: => Unit) - This method takes an identifier and a code block that will be measured. It simply calls the codeBlock, calculates how long it took to execute it and in the end it accumulates the result in the measurements map.
I think the method declaration requires a little more explanation. First it uses a feature called currying. For our purpose we can assume that it allows us to define function parameters in multiple parentheses pairs (of course currying is much more and it can be used for other purposes, but this is topic for other aricle) instead of one. Also codeBlock: => Unit part defines a function that takes no parameters, or just a code block surrounded by curly brackets { ... }.
Thanks to that we could call apply method in this way (full syntax):
apply("some computation")({complexComputation()})or we can omit latter parentheses and write simply:
apply("some computation"){complexComputation()}We wouldn't be able to do this, in such a nice way, if we would use only one parameters block, ie. apply(identifier:Any, codeBlock: => Unit)
- clearResults() - This method simply clears the measurements map to allow new measurements to be performed.
- result() - Returns a well formatted String representation of measurements result.
As you can see, the core imlpementation of this solution is very clear and simple. Also this is very easy to add new functionalities to this class.
Stopwatch companion object
This companion object is used to increase the ease of using Stopwatch class. It provides default instance of Stopwatch and provides a convenient methods to use it. To use those methods we have to import this object into current namespace by:
import Stopwatch._This import statement will include all methods from Stopwatch object into current namespace, so we can call it directly, without passing Stopwatch name.
ResultsFormatter class
This class is simpy used to create a well formatted String from Map containing measurement results.
Conclusion
I think that this approach to code performance measurement is well suited for many use cases, when you don't want to use external libraries for microbenchmarking or use of external profilers. Scala is very flexible language that allows us to create simple and very elegant solution for that kind of problems.Of course my Stopwatch is very simple, and I can imagine many ways to improve it. In example it can be rebuilt to be thread safe, or internal map can be replaced by simple array to increase its performance. But I also think that this is a good point to start for most of the projects.
Next article: Metaprogramming in Scala with higher order functions
Previous article: Scala - Parentheses and Curly Brackets in Anonymous Functions
great
ReplyDeleteThe article is so informative. This is more helpful for our
ReplyDeleteBest online software testing training course institute in chennai with placement
Best selenium testing online course training in chennai
Learn best software testing online certification course class in chennai with placement
Thanks for sharing.
Very useful and information content has been shared out here, Thanks for sharing it.
ReplyDeleteaws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
Thank you for sharing such a nice post!
ReplyDeleteLooking for Software Training in Bangalore , learn from Softgen Infotech Software Courses on online training and classroom training. Join today!
Thanks for sharing this blog. This very important and informative blog
ReplyDeletesap basis training in bangalore
sap mm training in bangalore
sap hana training in bangalore
sap fico training in bangalore
sap abap training in bangalore
I am really impressed the way you have written the blog Thank you so much for sharing the valueable post, I appreciate your hard work.Keep blogging.
ReplyDeleteAngular JS Training in Electronic City
Angular JS 2&4 Training in Electronic City
This is excellent information. It is amazing and wonderful to visit your site.
ReplyDeleteaws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore
I got useful information by reading this blogs
ReplyDeleteaws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore
Excellent post and I really glad to visit your post. Keep updating here...!
ReplyDeleteGraphic Design Courses in Chennai
Graphic Design Institute in Chennai
Unix Training in Chennai
Tableau Training in Chennai
Pega Training in Chennai
Linux Training in Chennai
Graphic Design Courses in Chennai
Placement Training in Chennai
Social Media Marketing Courses in Chennai
Power BI Training in Chennai
graphic design courses in tambaram
Great way to resolve the bug in program. Really useful. Thanks for posting.
ReplyDeletePython Training in Chennai | Certification | Online Course Training | Python Training in Bangalore | Certification | Online Course Training | Python Training in Hyderabad | Certification | Online Course Training | Python Training in Coimbatore | Certification | Online Course Training | Python Training in Online | Certification | Online Course Training
Thanks for sharing this information. I really Like Very Much.
ReplyDeletebest devops online training
Great awesome. This article is very nice content. thank you
ReplyDeletePython Training in Chennai | Certification | Online Training Course | Python Training in Bangalore | Certification | Online Training Course | Python Training in Hyderabad | Certification | Online Training Course | Python Training in Coimbatore | Certification | Online Training Course | Python Training in Online | Python Certification Training Course
This comment has been removed by the author.
ReplyDeleteI am really impressed the way you have written the blog Thank you so much for sharing the valueable post, I appreciate your hard work.Keep blogging.
ReplyDeletejava training in chennai
java training in omr
aws training in chennai
aws training in omr
python training in chennai
python training in omr
selenium training in chennai
selenium training in omr
Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site.
ReplyDeleteweb designing training in chennai
web designing training in omr
digital marketing training in chennai
digital marketing training in omr
rpa training in chennai
rpa training in omr
tally training in chennai
tally training in omr
Its is very very helpful for all of us. wonderful content. This Information Which You Shared Was Really Fantastic.
ReplyDeletehadoop training in chennai
hadoop training in tambaram
salesforce training in chennai
salesforce training in tambaram
c and c plus plus course in chennai
c and c plus plus course in tambaram
machine learning training in chennai
machine learning training in tambaram
Great. It is good to constantly coming up with creative ideas. Provides much needed knowledge. goal oriented blog posts and always tried to find creative ways to meet goals.
ReplyDeleteweb designing training in chennai
web designing training in tambaram
digital marketing training in chennai
digital marketing training in tambaram
rpa training in chennai
rpa training in tambaram
tally training in chennai
tally training in tambaram
Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
ReplyDeleteweb designing training in chennai
web designing training in porur
digital marketing training in chennai
digital marketing training in porur
rpa training in chennai
rpa training in porur
tally training in chennai
tally training in porur
I am so happy to found your blog post because it's really very informative. Please keep writing this kind of blogs and I regularly visit this blog. Have a look at my services.
ReplyDeleteI have found this Salesforce training in India worth joining course. Try this Salesforce training in Hyderabad with job assistance. Join Salesforce training institutes in ameerpet with certification. Enroll for Salesforce online training in hyderabad with hands on course.
The information you have given here are most worthy for me. I have implemented in my training program as well, thanks for sharing.
ReplyDeletehadoop training in chennai
hadoop training in velachery
salesforce training in chennai
salesforce training in velachery
c and c plus plus course in chennai
c and c plus plus course in velachery
machine learning training in chennai
machine learning training in velachery
I am really impressed with your efforts and really pleased to visit this post.
ReplyDeletesap training in chennai
sap training in annanagar
azure training in chennai
azure training in annanagar
cyber security course in chennai
cyber security course in annanagar
ethical hacking course in chennai
ethical hacking course in annanagar
I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday.
ReplyDeletesap training in chennai
sap training in annanagar
azure training in chennai
azure training in annanagar
cyber security course in chennai
cyber security course in annanagar
ethical hacking course in chennai
ethical hacking course in annanagar
This comment has been removed by the author.
ReplyDeleteGood Post! it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
ReplyDeleteAWS Training
Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the AWS Cloud Practitioner Online Training
ReplyDeleteGood blog, it's really very informative, do more blog under good concepts.
ReplyDeleteDigital Marketing Course in OMR
Digital Marketing Course in T Nagar
Digital Marketing Course in Anna Nagar
Digital Marketing Course in Velachery
Digital Marketing Course in Tambaram
Really, it’s a useful blog. Thanks for sharing this information.
ReplyDeleteR programming Training in Chennai
R programming Training in Bangalore
Xamarin Course in Chennai
Ionic Course in Chennai
ReactJS Training in Chennai
PLC Training in Chennai
Therefore my own preferred teaching technique is to provide employees with a MP3 player with a structured learning programme pre-loaded on it. Salesforce training in Hyderabad
ReplyDeleteVery excellent post!!! Thank you so much for your great content. Keep posting.....
ReplyDeletesalesforce training in chennai
software testing training in chennai
robotic process automation rpa training in chennai
blockchain training in chennai
devops training in chennai
Wow! Such an amazing and helpful post this is. I really really love it. I hope that you continue to do your work like this in the future also.
ReplyDeleteOnline Training for Big Data
Big Data Hadoop Online Training
It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read. Get for more information
ReplyDeleteJava Training in Chennai
Java Course in Chennai
Mua vé liên hệ đại lý Aivivu, tham khảo
ReplyDeletegiá vé máy bay đi Mỹ khứ hồi
giá vé từ mỹ về việt nam
vé máy bay khứ hồi từ đức về việt nam
chuyến bay nhật bản về việt nam
Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuff like this.
ReplyDeleteBest Training Institute for AWS in Pune
informative article
ReplyDeletebest-angular-training in chennai |
interesting to read.thank you
ReplyDeletebest-angular-training in chennai |
rastgele görüntülü konuşma - kredi hesaplama - instagram video indir - instagram takipçi satın al - instagram takipçi satın al - tiktok takipçi satın al - instagram takipçi satın al - instagram beğeni satın al - instagram takipçi satın al - instagram takipçi satın al - instagram takipçi satın al - instagram takipçi satın al - binance güvenilir mi - binance güvenilir mi - binance güvenilir mi - binance güvenilir mi - instagram beğeni satın al - instagram beğeni satın al - polen filtresi - google haritalara yer ekleme - btcturk güvenilir mi - binance hesap açma - kuşadası kiralık villa - tiktok izlenme satın al - instagram takipçi satın al - sms onay - paribu sahibi - binance sahibi - btcturk sahibi - paribu ne zaman kuruldu - binance ne zaman kuruldu - btcturk ne zaman kuruldu - youtube izlenme satın al - torrent oyun - google haritalara yer ekleme - altyapısız internet - bedava internet - no deposit bonus forex - erkek spor ayakkabı - webturkey.net - karfiltre.com - tiktok jeton hilesi - tiktok beğeni satın al - microsoft word indir - misli indir
ReplyDeleteyoutube abone satın al
ReplyDeletecami avizesi
cami avizeleri
avize cami
no deposit bonus forex 2021
takipçi satın al
takipçi satın al
takipçi satın al
takipcialdim.com/tiktok-takipci-satin-al/
instagram beğeni satın al
instagram beğeni satın al
btcturk
tiktok izlenme satın al
sms onay
youtube izlenme satın al
no deposit bonus forex 2021
tiktok jeton hilesi
tiktok beğeni satın al
binance
takipçi satın al
uc satın al
sms onay
sms onay
tiktok takipçi satın al
tiktok beğeni satın al
twitter takipçi satın al
trend topic satın al
youtube abone satın al
instagram beğeni satın al
tiktok beğeni satın al
twitter takipçi satın al
trend topic satın al
youtube abone satın al
takipcialdim.com/instagram-begeni-satin-al/
perde modelleri
instagram takipçi satın al
instagram takipçi satın al
takipçi satın al
instagram takipçi satın al
betboo
marsbahis
sultanbet
Data analyst generally works on creation of reports based on company’s data driven KPI’s(generally involves descriptive analytics), whereas Data scientists understand business and domain along with the technicalities to understand what will happen in future(more on descriptive + predictive analytics both)
ReplyDeleteEtlhive is a data science institute in pune. actuelly we wanted to promote our website on your site will you please contact me discus further details
website: - www.etlhive.com
contact: - +91 8055020011
December brings with it a special mood permeating the air around us. Yes! The world gears up to celebrate Christmas and the New Year that .
ReplyDeleteNew Year Quotes for Husband