使用Python线程会降低EC2性能吗?

时间:2019-10-22 18:50:32

标签: python django multithreading amazon-ec2 python-multithreading

我在REST端点中使用Python线程,以便该端点可以启动线程,然后在线程运行时立即向客户端返回200 OK。 (然后,客户端轮询服务器状态以跟踪线程的进度。)

代码在我的本地开发系统上运行需要7秒,而在AWS EC2 m5.large上则需要 6分钟

代码如下:

    import threading
    [.....]

    # USES THREADING
    # https://stackoverflow.com/a/1239108/364966
    thr = threading.Thread(target=score, args=(myArgs1, myArgs2), kwargs={})
    thr.start() # Will run "foo"
    thr.is_alive() # Will return whether function is running currently

    data = {'now creating test scores'}
    return Response(data, status=status.HTTP_200_OK)

我关闭线程以测试是否是导致速度变慢的原因,像这样:

    # USES THREADING
    # https://stackoverflow.com/a/1239108/364966
    # thr = threading.Thread(target=score, args=(myArgs1, myArgs2), kwargs={})
    # thr.start() # Will run "foo"
    # thr.is_alive() # Will return whether function is running currently

    # FOR DEBUGGING - SKIP THREADING TO SEE IF THAT'S WHAT'S SLOWING THINGS DOWN ON EC2
    score(myArgs1, myArgs2)

    data = {'now creating test scores'}
    return Response(data, status=status.HTTP_200_OK)

...它在EC2上运行了 5秒。这证明了我如何在EC2上处理线程的某些原因是导致速度变慢的原因。

我需要在EC2上进行一些配置以更好地支持Python线程吗?

1 个答案:

答案 0 :(得分:-1)

一位AWS认证的顾问建议我EC2为known to be slow in execution of Python threads,并改用AWS Lambda函数。