| 73836 |      1 | /*  Title:      Pure/ML/ml_profiling.scala
 | 
|  |      2 |     Author:     Makarius
 | 
|  |      3 | 
 | 
| 73840 |      4 | ML profiling (via Poly/ML run-time system).
 | 
| 73836 |      5 | */
 | 
|  |      6 | 
 | 
|  |      7 | package isabelle
 | 
|  |      8 | 
 | 
|  |      9 | 
 | 
|  |     10 | import java.util.Locale
 | 
|  |     11 | 
 | 
|  |     12 | import scala.collection.immutable.SortedMap
 | 
|  |     13 | 
 | 
|  |     14 | 
 | 
| 75393 |     15 | object ML_Profiling {
 | 
|  |     16 |   sealed case class Entry(name: String, count: Long) {
 | 
| 73836 |     17 |     def clean_name: Entry = copy(name = """-?\(\d+\).*$""".r.replaceAllIn(name, ""))
 | 
|  |     18 | 
 | 
|  |     19 |     def print: String =
 | 
| 73843 |     20 |       String.format(Locale.ROOT, "%12d %s",
 | 
| 73836 |     21 |         count.asInstanceOf[AnyRef], name.asInstanceOf[AnyRef])
 | 
|  |     22 |   }
 | 
|  |     23 | 
 | 
| 75393 |     24 |   sealed case class Report(kind: String, entries: List[Entry]) {
 | 
| 73836 |     25 |     def clean_name: Report = copy(entries = entries.map(_.clean_name))
 | 
|  |     26 | 
 | 
|  |     27 |     def total: Entry = Entry("TOTAL", entries.iterator.map(_.count).sum)
 | 
|  |     28 | 
 | 
|  |     29 |     def print: String =
 | 
| 73840 |     30 |       ("profile_" + kind + ":\n") + cat_lines((entries ::: List(total)).map(_.print))
 | 
| 73836 |     31 |   }
 | 
|  |     32 | 
 | 
| 75393 |     33 |   def account(reports: List[Report]): List[Report] = {
 | 
| 73836 |     34 |     val empty = SortedMap.empty[String, Long].withDefaultValue(0L)
 | 
|  |     35 |     var results = SortedMap.empty[String, SortedMap[String, Long]].withDefaultValue(empty)
 | 
|  |     36 |     for (report <- reports) {
 | 
|  |     37 |       val kind = report.kind
 | 
|  |     38 |       val map = report.entries.foldLeft(results(kind))(
 | 
|  |     39 |         (m, e) => m + (e.name -> (e.count + m(e.name))))
 | 
|  |     40 |       results = results + (kind -> map)
 | 
|  |     41 |     }
 | 
|  |     42 |     for ((kind, map) <- results.toList)
 | 
|  |     43 |       yield Report(kind, for ((name, count) <- map.toList.sortBy(_._2)) yield Entry(name, count))
 | 
|  |     44 |   }
 | 
|  |     45 | }
 |