0

情况就是这样:

我的程序需要 Y 长度数组的 X 个随机元素。X 总是低于 Y

所以我做什么:方式#1:

1. shuffle the array
2. get the X elements from index 0 to X-1
3. (back to step 1) repeat like 2.000.000 times or more.

因为改组数组需要大量资源,所以我想让我的程序更快。我想到了这样的事情:

方式#2:

1. find out how often X fits into Y (asume X = 6, and X = 20)
2. shuffle the array
3a. get the X elements from index 0 to 5
3b. get the X elements from index 6 to 11
3c. get the X elements from index 12 to 17
(index 18 and 19 will not be used in this case)
4. (back to step 2) repeat like 2.000.000 times or more.

经过一些试验,我得到了两种方式的预期结果到小数点后第三位。这对我的目的来说绝对没问题。

WAY#2 比 WAY#1 快 25-30%

你怎么看?我应该接受一点点掺假以获得更高的性能,还是只是坏习惯,应该避免?

4

0 回答 0