前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >业务代码耗时操作优化

业务代码耗时操作优化

作者头像
用户4945346
发布2020-06-16 10:00:25
6780
发布2020-06-16 10:00:25
举报
文章被收录于专栏:pythonista的日常

前几天我把我们小程序登录接口性能优化了,优化之前登录接口响应时间大概是 300 ms 左右,优化后的响应时间大概在 70 ms 左右。我们小程序登录接口涉及到的业务操作除了基本的登录验证功能外还加了个用户小程序openid的获取和保存操作。我为每个功能都用 time 方法打印了各自操作的耗时,通过比对耗时发现是获取用户 openid 的操作比较耗时,因为涉及到了向微信发送 request 的请求以及等待微信的请求响应,所有我就把获取用户 openid 这块用异步方法实现,借助的模块是 threading 中 Timer 类。

先看下 Time 简单使用

代码语言:javascript
复制
import time
from threading import Timer

def test_timer():
    print("start=======")
    t1 = time.time()
    time.sleep(3)
    print("ok")
    t2 = time.time()
    t21 = t2 - t1
    print('t21====', t21)

def async_test_timer():
    Timer(1, test_timer, []).start()

if __name__ == "__main__":
    tm1 = time.time()
    time.sleep(1)
    async_test_timer()
    tm2 = time.time()
    tm21 = tm2 - tm1
    print('tm21=====', tm21)

上面代码的执行结果为:

代码语言:javascript
复制
tm21===== 1.0052900314331055
start=======
ok
t21==== 3.0050549507141113

上面的代码是先打印了 tm21 ,然后再执行了 async_test_timer 函数,Timer 类表示一个动作应该在一个特定的时间之后运行 — 也就是一个计时器。Timer是Thread的子类, 因此也可以使用函数创建自定义线程。它是异步的,用它处理耗时的操作很方便。第一个参数是多少秒后执行,第二个参数是函数名,第三个参数是要异步执行的函数所需的参数。

下面附 Timer 类的源码,它继承了 Thread 类。

代码语言:javascript
复制
class Timer(Thread):
    """Call a function after a specified number of seconds:

            t = Timer(30.0, f, args=None, kwargs=None)
            t.start()
            t.cancel()     # stop the timer's action if it's still waiting

    """

    def __init__(self, interval, function, args=None, kwargs=None):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args if args is not None else []
        self.kwargs = kwargs if kwargs is not None else {}
        self.finished = Event()


class Thread:
    """A class that represents a thread of control.

    This class can be safely subclassed in a limited fashion. There are two ways
    to specify the activity: by passing a callable object to the constructor, or
    by overriding the run() method in a subclass.

    """

    _initialized = False
    # Need to store a reference to sys.exc_info for printing
    # out exceptions when a thread tries to use a global var. during interp.
    # shutdown and thus raises an exception about trying to perform some
    # operation on/with a NoneType
    _exc_info = _sys.exc_info
    # Keep sys.exc_clear too to clear the exception just before
    # allowing .join() to return.
    #XXX __exc_clear = _sys.exc_clear

    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, *, daemon=None):
        """This constructor should always be called with keyword arguments. Arguments are:

        *group* should be None; reserved for future extension when a ThreadGroup
        class is implemented.

        *target* is the callable object to be invoked by the run()
        method. Defaults to None, meaning nothing is called.

        *name* is the thread name. By default, a unique name is constructed of
        the form "Thread-N" where N is a small decimal number.

        *args* is the argument tuple for the target invocation. Defaults to ().

        *kwargs* is a dictionary of keyword arguments for the target
        invocation. Defaults to {}.

        If a subclass overrides the constructor, it must make sure to invoke
        the base class constructor (Thread.__init__()) before doing anything
        else to the thread.

        """
        assert group is None, "group argument must be None for now"
        if kwargs is None:
            kwargs = {}
        self._target = target
        self._name = str(name or _newname())
        self._args = args
        self._kwargs = kwargs
        if daemon is not None:
            self._daemonic = daemon
        else:
            self._daemonic = current_thread().daemon
        self._ident = None
        self._tstate_lock = None
        self._started = Event()
        self._is_stopped = False
        self._initialized = True
        # sys.stderr is not stored in the class like
        # sys.exc_info since it can be changed between instances
        self._stderr = _sys.stderr
        # For debugging and _after_fork()
        _dangling.add(self)
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-11-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 pythonista的日常 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
访问管理
访问管理(Cloud Access Management,CAM)可以帮助您安全、便捷地管理对腾讯云服务和资源的访问。您可以使用CAM创建子用户、用户组和角色,并通过策略控制其访问范围。CAM支持用户和角色SSO能力,您可以根据具体管理场景针对性设置企业内用户和腾讯云的互通能力。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档