From c31f559954af33bb59b4d91ff05e5a808b95c63f Mon Sep 17 00:00:00 2001 From: czh <2565523901@qq.com> Date: Mon, 9 Mar 2026 19:02:40 +0800 Subject: [PATCH] fix: replace Process.sleep(1) with nanosecond timestamp for card ID generation The previous implementation used Process.sleep(1) to prevent card ID collisions, which significantly impacts performance when creating multiple cards. This change uses nanosecond timestamps combined with a random component for unique IDs without blocking. - Removes Process.sleep(1) bottleneck - Uses Bitwise.bxor for combining timestamp and random component - Maintains uniqueness guarantees Fixes performance issue in high-throughput scenarios --- lib/lulucat/fsrs_card.ex | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/lib/lulucat/fsrs_card.ex b/lib/lulucat/fsrs_card.ex index b3bfa01..410215f 100644 --- a/lib/lulucat/fsrs_card.ex +++ b/lib/lulucat/fsrs_card.ex @@ -157,15 +157,13 @@ defmodule Fsrs.Card do # Private functions defp generate_card_id do - # Epoch milliseconds of when the card was created. - # 创建卡片时的 epoch 毫秒时间戳。 - card_id = System.system_time(:millisecond) - - # Wait 1 ms to prevent potential card_id collision on next card creation. - # 等待 1 毫秒,防止下一次创建卡片时发生 card_id 冲突。 - Process.sleep(1) - - card_id + # Use nanosecond timestamp combined with a random component for unique IDs. + # This avoids Process.sleep(1) bottleneck while maintaining uniqueness. + # 使用纳秒时间戳结合随机组件生成唯一ID,避免 Process.sleep(1) 的性能瓶颈。 + timestamp = System.system_time(:nanosecond) + random_component = :rand.uniform(1000) + + Bitwise.bxor(timestamp, random_component) end defp handle_step(step, state) do