alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (Statistics.scala)

This example Scala source code file (Statistics.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

hashmap, int, int, iterable, long, long, statistics, statistics, string, t, t, unit

The Scala Statistics.scala source code

/* NEST (New Scala Test)
 * Copyright 2007-2011 LAMP/EPFL
 * @author Philipp Haller
 */

package scala.tools
package partest

import scala.collection.mutable.HashMap

trait Statistics {  
  /** Only collected when --stats is given. */
  lazy val testStatistics = new HashMap[String, Long]

  /** Given function and block of code, evaluates code block,
   *  calls function with milliseconds elapsed, and returns block result.
   */
  def timed[T](f: Long => Unit)(body: => T): T = {
    val start = System.currentTimeMillis
    val result = body
    val end = System.currentTimeMillis
    
    f(end - start)
    result
  }
  /** Times body and returns both values.
   */
  def timed2[T](body: => T): (Long, T) = {
    var milliSeconds = 0L
    val result = timed(x => milliSeconds = x)(body)
    
    (milliSeconds, result)
  }
  
  def resultsToStatistics(results: Iterable[(_, Int)]): (Int, Int) =
    (results partition (_._2 == 0)) match { 
      case (winners, losers) => (winners.size, losers.size)
    }

  def recordTestTiming(name: String, milliseconds: Long) =
    synchronized { testStatistics(name) = milliseconds }

  def showTestStatistics() {
    testStatistics.toList sortBy (-_._2) foreach { case (k, v) => println("%s: %.2f seconds".format(k, (v.toDouble / 1000))) }
  }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala Statistics.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.