jeudi 11 août 2016

For loop advancing too quickly without generating random strings properly [duplicate]

This question already has an answer here:

So I coded a quick program to test how much difference it would make (in terms of processing speed) to check a boolean inside a foreach statement compared to checking it in a conditional statement outside of the loop. To test this I made a function generate random strings and add them to a list, but the for loop that generates the strings seems to advance too quickly without generating different strings in ever repetition. To fix this I added a Thread.Sleep(15) (15 milliseconds seems to be the minimum required to generate a different string in every repetition).

My question is this: is it possible to fix this issue without a Thread.Sleep(15)? Waiting 15 milliseconds between every repetition makes it so that the program takes a way bigger amount of time to run, which makes it highly unpractical for it's purpose (if I want to get statistically relevant data I'd have to run it around 10 thousand times for each option (the "good" and the "bad" way)). Here's the for loop in question:

for (int i = 0; i < 1000; i++) {

                var stringChars = new char[8];
                var random = new Random();

                for (int n = 0; n < stringChars.Length; n++)
                {
                    stringChars[n] = chars[random.Next(chars.Length)];
                }

                var finalString = new String(stringChars);
                data.Add(finalString);
                Thread.Sleep(15);
        }




Aucun commentaire:

Enregistrer un commentaire