使用Python编写的gRPC如何测量响应时间?

3

我怎么能测量grpc-python处理请求所需的全部时间?到目前为止,我能做到的最好的是:

def Run(self, request, context):
   start = time.time()
   # service code...
   end = time.time()
   return myservice_stub.Response()

但是这并不能测量grpc在序列化请求、响应、传输到网络上所花费的时间等等。我正在寻找一种“钩入”这些步骤的方法。


你尝试过查看文档吗?https://grpc.io/docs/languages/python/basics/#request-streaming-rpc - SaaSy Monster
是的,没有找到。而且这个链接并没有回答我的问题,它只是测量请求处理程序中的Python代码。 - user3599803
你可以尝试在调用Run(self, request, context)方法之前和之后添加time.time() - Ajay A
你在这里想要实现什么目标?这是为了做基准测试吗? - gergelykalman
是的。我正在尝试弄清楚grpc序列化的开销以及在我的实际代码之前运行的其他内容。 - user3599803
2个回答

0
你可以使用拦截器来实现这个功能。grpc-interceptors 包简化了拦截器的创建。
import logging
import time
from typing import Callable, Any
import grpc

class RequestLoggingInterceptor(ServerInterceptor):
    def intercept(
        self,
        method: Callable,
        request: Any,
        context: grpc.ServicerContext,
        method_name: str,
    ) -> Any:
        start_time = time.monotonic()
        ip = context.peer().split(":")[1]

        try:
            start = datetime.now()
            return method(request, context)
        finally:
            request_time = time.monotonic() - start_time
            logging.info(
                f"{ip} -- {datetime.now()} -- {method_name} -- {request_time}s"
            )

0

你可以在客户端测量:

start = time.time()
response = stub.Run(request)
total_end_to_end = time.time() - start

然后,通过减少Run方法的计算,您可以获得总开销(序列化,传输)。

为了自动化该过程,您可以将计算时间作为myservice_stub.Response中的字段添加(至少为测试而添加)。


我已经完成了,但这将包括服务器上的网络+开销。我希望仅测量服务器上的开销。 - user3599803

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接