如何测量 Cats IO 效果中的经过时间?

问题描述 投票:0回答:2

我想测量 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")
    }
  }
}

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

谢谢!

scala functional-programming scala-cats cats-effect
2个回答
8
投票

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

0
投票

在猫效果3中,您可以使用

.timed
。喜欢,

import cats.effect.IO
import cats.effect.unsafe.implicits.global
import cats.implicits._
import scala.concurrent.duration._

val twoSecondsLater = IO.sleep(2.seconds) *> IO.println("Hi")

val elapsedTime = twoSecondsLater.timed.map(_._1)
elapsedTime.unsafeRunSync()

// would give something like this. 
Hi
res0: FiniteDuration = 2006997667 nanoseconds

© www.soinside.com 2019 - 2024. All rights reserved.