• 凯哥带你用python撸算法之雪花算法


    import time
     
     
    class Snow(object):
     
        def __init__(self, idx=None):
            init_date = time.strptime('2010-01-01 00:00:00', "%Y-%m-%d %H:%M:%S")
            self.start = int(time.mktime(init_date))
            self.last = int(time.time())
            self.count_id = 0
            self.idx = idx if idx else 0
     
        def get(self):
            now = int(time.time())
            temp = now - self.start
            if len(str(temp)) < 9:
                length = len(str(temp))
                s = '0' * (9 - length)
                temp = s + str(temp)
            if now == self.last:
                self.count_id += 1
            else:
                self.count_id = 0
                self.last = now
            if len(str(self.idx)) < 2:
                length = len(str(self.idx))
                s = '0' * (2 - length)
                self.idx = s + str(self.idx)
            if self.count_id == 99999:
                time.sleep(1)
            count_id_data = str(self.count_id)
            if len(count_id_data) < 5:
                length = len(count_id_data)
                s = '0' * (5 - length)
                count_id_data = s + count_id_data
            return ''.join([temp, self.idx, count_id_data])
     
     
    if __name__ == '__main__':
        import threading
        snow = Snow('001')
     
        def echo():
            print(snow.get())
     
        threads = [threading.Thread(target=echo) for i in range(100)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
    
  • 相关阅读:
    设计模式
    Lambda表达式
    网络通信
    排序
    可变参数
    反弹shell学习总结
    Apache Flink任意Jar包上传导致远程代码执行漏洞复现
    定时执行rsync同步数据以及mysql备份
    python练习
    django 模型生成sql(多对多)
  • 原文地址:https://www.cnblogs.com/qianzhengkai/p/11428468.html
Copyright © 2020-2023  润新知