Azure 应用服务上的 Python 代码运行速度比本地慢 10 倍

标签 python django azure azure-web-app-service

我有一个小型 django 应用程序,托管在应用服务上。我注意到它在应用服务上的运行速度比本地完全相同的代码慢得多。我没有看到任何错误,应用服务指标看起来也没有异常。关于如何解决这个问题有什么建议吗?

下面是一个运行速度慢 10 倍的示例函数(所有本地测试不到 1 秒,在应用服务上最多 10-20 秒)。

def check_regex(voice_input, phrase, errors_allowed=4):
    print("START REGEX")
    search_str = "(%s){e<%i}" % (phrase, errors_allowed)
    regex_result = regex.search(
        search_str,
        voice_input,
        flags=regex.IGNORECASE)
    if regex_result is not None:
        print(f"REGEX CHECK: {voice_input} and {phrase}")
        print(regex_result)
        return True
    else:
        print("NO MATCH")
        return False

最佳答案

您可以在功能 block 外部添加编译正则表达式方法,这将预编译该方法,删除打印语句这将减少 I/O 开销并优化代码,如下所示:-

# Pre-compile the regex pattern outside the function
compiled_pattern = regex.compile("({}){{e<{}}}".format(phrase, errors_allowed), flags=regex.IGNORECASE)

def check_regex(voice_input, phrase, errors_allowed=4):
    # Commented out print statements for improved performance
    # print("START REGEX")
    regex_result = compiled_pattern.search(voice_input)
    if regex_result is not None:
        # print(f"REGEX CHECK: {voice_input} and {phrase}")
        # print(regex_result)
        return True
    else:
        # print("NO MATCH")
        return False

为了深入了解您的应用服务运行缓慢,请尝试 Monitor并检查您的 Web 应用程序的日志并启用 Application Insights为您的 Web 应用程序获取如下性能图表:-

enter image description here

启用应用程序服务日志,如下所示:-

enter image description here

访问开发工具 > 高级工具 > Go > 在 kudu 控制台中选择当前 Docker 日志(下载为 zip)并检查日志,您也可以通过此 Rest API 调用下面的日志。

enter image description here

一种方法是选择“诊断和解决问题”,然后选择“可用性和性能”选项卡来获取日志和见解:-

enter image description here

enter image description here

向下滚动并选择“查看解决方案”以解决网络应用速度缓慢的问题:-

enter image description here

检查应用程序日志和 I/O:-

enter image description here

关于Azure 应用服务上的 Python 代码运行速度比本地慢 10 倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76658470/

相关文章:

python - 在Python中使用for循环生成动态嵌套JSON

python - 值错误 : invalid literal for int() with base 10: 'Blusson Hall'

python - 在电子邮件上制作 Django 的身份验证跟踪,如何将用户名字段与电子邮件相关联?

azure - Team Foundation Service 构建完成后添加 Fluent Migrator 迁移步骤

azure - 如何在从 Azure Key Vault 更新 secret 时自动重新启动 Pod/部署

asp.net - Azure 网站 - 最大限度地减少小而频繁的中断

python - numpy bincount - 选择最大权重而不是对所有权重求和

python - 如何输出分组对象中指定列中所有值的列表

python - 在 django rest framework 3 中使用可写嵌套序列化程序创建多个对象

django - 你如何让 Django-admin 时区知道?