cyr*_*llk 2 functional-programming scala scala-cats cats-effect
我想测量 IO 容器内经过的时间。使用普通调用或期货相对容易(例如,类似于下面的代码)
class MonitoringComponentSpec extends FunSuite with Matchers with ScalaFutures {
import scala.concurrent.ExecutionContext.Implicits.global
def meter[T](future: Future[T]): Future[T] = {
val start = System.currentTimeMillis()
future.onComplete(_ => println(s"Elapsed ${System.currentTimeMillis() - start}ms"))
future
}
def call(): Future[String] = Future {
Thread.sleep(500)
"hello"
}
test("metered call") {
whenReady(meter(call()), timeout(Span(550, Milliseconds))) { s =>
s should be("hello")
}
}
}
Run Code Online (Sandbox Code Playgroud)
但不确定如何包装 IO 调用
def io_meter[T](effect: IO[T]): IO[T] = {
val start = System.currentTimeMillis()
???
}
def io_call(): IO[String] = IO.pure {
Thread.sleep(500)
"hello"
}
test("metered io call") {
whenReady(meter(call()), timeout(Span(550, Milliseconds))) { s =>
s should be("hello")
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Cats-effect 有一个Clock实现,它允许纯时间测量以及在您只想模拟时间流逝时注入您自己的实现进行测试。他们文档中的示例是:
def measure[F[_], A](fa: F[A])
(implicit F: Sync[F], clock: Clock[F]): F[(A, Long)] = {
for {
start <- clock.monotonic(MILLISECONDS)
result <- fa
finish <- clock.monotonic(MILLISECONDS)
} yield (result, finish - start)
}
Run Code Online (Sandbox Code Playgroud)