scala - 如何测量 Cats IO 效果中的耗时?

标签 scala functional-programming scala-cats cats-effect

我想测量 IO 容器内耗时。使用普通调用或 future 相对容易(例如下面的代码)

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")
    }
  }
}

但不确定如何包装 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")
    }
  }

谢谢!

最佳答案

猫效应有一个 Clock允许纯时间测量的实现,以及在您只想模拟时间流逝时注入(inject)您自己的实现以进行测试。他们文档中的示例是:

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)
}

关于scala - 如何测量 Cats IO 效果中的耗时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54830287/

相关文章:

scala - 在 Scala 中编写一个通用的均值函数

Scalaz 与 ReactiveX

python映射字符串拆分列表

haskell - 等效于具有停止条件的发电机的 Haskell

ios - 函数作为参数的未解析标识符

scala - 运行 future 后返回 IO 光纤/线程

scala - 新版本的 fs2 (0.10.x) 中的 fs2.Scheduler 等效于什么

scala - 您在哪里拆分长Scala函数签名?

scala - 为什么猫的效果异步签名使用 Either[Throwable, A] 而不是 Try[A]?

Scaladoc 无法为方法和类签名中的内部类生成链接