Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using clock ticks as random number seed

I'm using the current clock ticks as a seed for random number generation. The random number is used in a pseudo GUID and a check in my database will make sure it doesn't already exist before returning. On average, this method will be called around 10k times in succession during the life of the process.

My concern is that an identical number might be generated back to back resulting in multiple unnecessary recursive calls to my database checking for the same ID. I'd like to avoid this if possible. What is the best way to test this scenario?

If it matters, application is .NET 4 and database is SQL Server 2008.

private static string GenerateUniqueDelId()
{
    // Generate a random integer using the current number of clock ticks as seed.
    // Then prefix number with "DEL" and date, finally padding random integer with leading zeros for a fixed 25-character total length.
    int seed = (int)DateTime.Now.Ticks;
    Random number = new Random(seed);
    string id = string.Format("DEL{0}{1}", DateTime.Today.ToString("yyyyMMdd"), number.Next().ToString("D14"));

    // Lookup record with generated ID in Sesame. If one exists, call method recursively.
    string query = "SELECT * FROM Lead WHERE Esm_Id = @Esm_Id";
    SqlParameter[] parameters = { new SqlParameter("@Esm_Id", id) };
    if (DataManager.GetRow(query, parameters, DelConnection.Sesame) != null) return GenerateUniqueDelId();

    // Otherwise, return ID.
    return id;
}   //// End GenerateUniqueDelId()
like image 981
Brian Avatar asked Jun 05 '12 19:06

Brian


People also ask

What is a good seed for random number generator?

Many researchers worry about how to choose a random number seed. Some people use an easy-to-remember sequence such as their phone number or the first few digits of pi. Others use long prime numbers such as 937162211.

How do you calculate random seed?

Step 1: Type “=RANDBETWEEN(a,b)” into an empty cell, where a,b is the range you want to pick numbers from. For example, =RANDBETWEEN(1,100) will generate a random number between 1 and 100. Step 2: Press “ENTER.” This generates a random number between the number you specified.

How are random seeds generated?

Random seeds are often generated from the state of the computer system (such as the time), a cryptographically secure pseudorandom number generator or from a hardware random number generator.

Why do random number generators need to be seeded?

The seed is a starting point for a sequence of pseudorandom numbers. If you start from the same seed, you get the very same sequence. This can be quite useful for debugging. If you want a different sequence of numbers each time, you can use the current time as a seed.


2 Answers

You are right in your concern: You should move the creation of your Random instance out of your method body - otherwise you will re-seed with the same value many times which results in the same number sequence.

Also you are kinda re-inventing the wheel: the default constructor of the Random class already uses the current clock time as default seed.

The question is why don't you avoid all of this and just use an auto-generated Guid on the database side?

like image 132
BrokenGlass Avatar answered Nov 08 '22 14:11

BrokenGlass


Quoting Jon Skeet

When you see the word "random" in a question title on Stack Overflow you can almost guarantee it will be the same fundamental problem as countless similar questions. This article takes a look at why randomness causes so many problems, and how to address them.

Check his article about random number generators

http://csharpindepth.com/Articles/Chapter12/Random.aspx

basically his solution looks like:

using System;
using System.Threading;

public static class RandomProvider
{    
    private static int seed = Environment.TickCount;

    private static ThreadLocal<Random> randomWrapper = new ThreadLocal<Random>(() =>
        new Random(Interlocked.Increment(ref seed))
    );

    public static Random GetThreadRandom()
    {
        return randomWrapper.Value;
    }
}
like image 20
Jupaol Avatar answered Nov 08 '22 15:11

Jupaol