summaryrefslogtreecommitdiff
path: root/src/partest-alternative/scala/tools/partest/Statistics.scala
blob: 2ea3c6e8f0d8be087f7f5ef842978160e58b6fb4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* NEST (New Scala Test)
 * Copyright 2007-2010 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))) }
  }
}