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
ReplyDeleteIEEE Final Year Project centers make amazing deep learning final year projects ideas for final year students Final Year Projects for CSE to training and develop their deep learning experience and talents.
DeleteIEEE Final Year projects Project Centers in India are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation.
corporate training in chennai corporate training in chennai
corporate training companies in india corporate training companies in india
corporate training companies in chennai corporate training companies in chennai
I have read your blog its very attractive and impressive. I like it your blog. Digital Marketing Company in Chennai Project Centers in Chennai
Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru JavaScript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai
ReplyDeleteThis is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me..
ReplyDeleteBest Devops online Training
Online DevOps Certification Course - Gangboard
Yeah polazila today all day on the Internet heard that you can earn some money while sitting at home and only this site proved it to me super play casino games for fun Have you been to this site?
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.
ReplyDeletethanks for your information really good and very nice web design company in velachery
Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
ReplyDeleteJava Training in Chennai
Java Training in Coimbatore
Java Training in Bangalore
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!
Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site.
ReplyDeleteSAP PP Training in Bangalore
sap s4 hana training in bangalore
sap bw training in bangalore
sap sd training in bangalore
sap hr training in bangalore
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
Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site.Prathima Infotech training center bangalore
ReplyDeleteSAP APO Training in Bangalore
sap gts training in bangalore
sap testing training in bangalore
sap fiori 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
Wonderful blog with great piece of information. Regards to your effort. Keep sharing more such blogs.Looking forward to learn more from you.
ReplyDeleteoracle training in chennai
oracle training in porur
oracle dba training in chennai
oracle dba training in porur
ccna training in chennai
ccna training in porur
seo training in chennai
seo training in porur
Myself so glad to establish your blog entry since it's actually quite instructive. If it's not too much trouble continue composing this sort of web journal and I normally visit this blog. Examine my administrations.
ReplyDeleteGo through these Salesforce Lightning Features course. Found this Salesforce CRM Using Apex And Visualforce Training worth joining. Enroll for SalesForce CRM Integration Training Program and practice well.
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.
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
This is the information that ive been looking for. Great insights & you have explained it really well. Thank you & looking forward for more of such valuable updates.
ReplyDeletedata science training in chennai
data science training in velachery
android training in chennai
android training in velachery
devops training in chennai
devops training in velachery
artificial intelligence training in chennai
artificial intelligence 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
Myself so glad to establish your blog entry since it's actually quite instructive. If it's not too much trouble continue composing this sort of web journal and I normally visit this blog. Examine my administrations.
ReplyDeleteRead these Salesforce Admin Certification Topics which are really helpful. I read these Salesforce Admin and Developer Certification Dumps and very much useful for me.
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 readers....thanks for sharing it and do share more posts like this.
ReplyDeleteData Science Online 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
ReplyDeleteThe Key Stones behind the success to become a Salesforce Professional lies in the programming skills, analytical skills, ability to ask the right questions and interesting to learn, willingness to work hard and put in long hours and confident. Salesforce training in Chennai
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
ReplyDeleteThanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
ReplyDeleteangular js online training
best angular js online training
top angular js online training
Thanks for Sharing This Article.It is very much valuable content.
ReplyDeletetips for content writing
seo content writing samples
german language to english
salesforce basics
star certification
ethical hacking books
Very 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
Thanks for sharing all the information with us all.
ReplyDeleteData Science Online Training
Python Online Training
Salesforce Online Training
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
I read your article it is very interesting and every concept is very clear, thank you so much for sharing. AWS Certification Course in Chennai
ReplyDeletehttps://designingcourses.in/
ReplyDeleteVery Informative and useful... Keep it up the great work. I really appreciate your post.
graphic designing courses in Bangalore
web designing course in Bangalore
UX Design course in Bangalore
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 |
Its always nice and i feel honored reading your Blog . Your Blogs always based on all basic concepts which anyone can understand so easily and relate to Pleasure to read your Blogs Sir.
ReplyDeletegolden retriever puppies for sale
golden retriever puppies for sale in pa
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
marsbahis
ReplyDeletebetboo
sultanbet
marsbahis
betboo
sultanbet
tiktok jeton hilesi
ReplyDeletetiktok jeton hilesi
binance referans kimliği
gate güvenilir mi
tiktok jeton hilesi
paribu
btcturk
bitcoin nasıl alınır
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
instagram takipçi satın al
ReplyDelete