samedi 22 août 2015

faster random generator on List

first the question is about performance can i make the random generation any faster?, given that: i am implementing a .Shufle() Extention method(found in SO) though when used properly (giving little time to regenerate) it gets real slow, as my needs are to repeate the genaration in a for loop over 1k times on each seed set.

say the 'banks' are

List<int> seedLst1 = new List<int>(){2, 4, 6, 8, 10.....}
List<int> seedLst2 = new List<int>(){10, 15, 20, 11, 22, 33.....}

so i call them in as parameter(within a container)

List<List<int>> allSeedSetsLst 

//randsPerSet - how many random items in each resultset
//count - total iteration on each of the sorces

List<List<int>> getRandRes(List<List<int>> SeedsBank, int count, int randsperSet)
{
    List<List<int>> RetGuessList = new List<List<int>>();

    foreach (var CurSeedLst in SeedsBank)
    {
        int randomIntrval = 55;
        List<int> curRandSet;
        for (i=0; i < count; i++)
        {
            curRandSet = new List<int>();

            System.Threading.Thread.Sleep(randomInterval * 15);
            curRandSet = CurSeedLst.Shuffle().Take(randsperSet);

            randomInterval = curRandSet.Last();

            RetGuessList.Add(curRandSet);
        }
    }
    return RetGuessList;
}

the shufle code

public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
    return source.Shuffle(new Random());
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
    if (source == null) throw new ArgumentNullException("source");
    if (rng == null) throw new ArgumentNullException("rng");

    return source.ShuffleIterator(rng);
}

private static IEnumerable<T> ShuffleIterator<T>(this IEnumerable<T> source, Random rng)
{
    List<T> buffer = source.ToList();
    for (int i = 0; i < buffer.Count; i++)
    {
        int j = rng.Next(i, buffer.Count);
        yield return buffer[j];

        buffer[j] = buffer[i];
    }
}




Aucun commentaire:

Enregistrer un commentaire