我需要计算scala中代码的运行时间。代码是。
val data = sc.textFile("/home/david/Desktop/Datos Entrada/household/household90Parseado.txt")
val parsedData = data.map(s => Vectors.dense(s.split(' ').map(_.toDouble))).cache()
val numClusters = 5
val numIterations = 10
val clusters = KMeans.train(parsedData, numClusters, numIterations)
我需要知道运行时来处理这段代码,时间必须是秒。 非常感谢你。
答案 0 :(得分:24)
根据讨论here,您需要使用System.nanoTime
来衡量已用时差:
val t1 = System.nanoTime
/* your code */
val duration = (System.nanoTime - t1) / 1e9d
答案 1 :(得分:5)
您可以使用scalameter:https://scalameter.github.io/
只需将代码块放在括号中:
val executionTime = measure {
//code goes here
}
您可以将其配置为预热jvm,以便测量更可靠:
val executionTime = withWarmer(new Warmer.Default) measure {
//code goes here
}
答案 2 :(得分:4)
从 Spark2
开始,我们可以使用 spark.time(<command>)
(仅在scala中使用)来获取执行动作/转化 ..
示例:
发现数量records in a dataframe
scala> spark.time(
sc.parallelize(Seq("foo","bar")).toDF().count() //create df and count
)
Time taken: 54 ms //total time for the execution
res76: Long = 2 //count of records
答案 3 :(得分:4)
/**
* Executes some code block and prints to stdout the time taken to execute the block. This is
* available in Scala only and is used primarily for interactive testing and debugging.
*
*/
def time[T](f: => T): T = {
val start = System.nanoTime()
val ret = f
val end = System.nanoTime()
println(s"Time taken: ${(end - start) / 1000 / 1000} ms")
ret
}
用法:
time {
Seq("1", "2").toDS().count()
}
//Time taken: 3104 ms
> = Spark 2.1.0 SparkSession
您可以使用spark.time
用法:
spark.time {
Seq("1", "2").toDS().count()
}
//Time taken: 3104 ms
答案 4 :(得分:3)
最基本的方法是简单地记录开始时间和结束时间,并进行减法。
val startTimeMillis = System.currentTimeMillis()
/* your code goes here */
val endTimeMillis = System.currentTimeMillis()
val durationSeconds = (endTimeMillis - startTimeMillis) / 1000
答案 5 :(得分:0)
这将是计算Scala代码时间的最佳方法。
def time[R](block: => (String, R)): R = {
val t0 = System.currentTimeMillis()
val result = block._2
val t1 = System.currentTimeMillis()
println(block._1 + " took Elapsed time of " + (t1 - t0) + " Millis")
result
}
result = kuduMetrics.time {
("name for metric", your function call or your code)
}