1. 程式人生 > >python實現的雪花演算法一枚

python實現的雪花演算法一枚

資料量寫入很大的場景使用

優點: 提高寫入效率

# coding: utf-8

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()