我有一个小型 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 应用程序获取如下性能图表:-
启用应用程序服务日志,如下所示:-
访问开发工具 > 高级工具 > Go > 在 kudu 控制台中选择当前 Docker 日志(下载为 zip)并检查日志,您也可以通过此 Rest API 调用下面的日志。
一种方法是选择“诊断和解决问题”,然后选择“可用性和性能”选项卡来获取日志和见解:-
向下滚动并选择“查看解决方案”以解决网络应用速度缓慢的问题:-
检查应用程序日志和 I/O:-
关于Azure 应用服务上的 Python 代码运行速度比本地慢 10 倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76658470/