由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - Shuffle performance (C#)
相关主题
求问一道数组shuffle的问题 (转载)两行quicksort,不难些吧
一个搞统计的对C#的第一印象does the system guarantee this? (转载)
[合集] 面试问题multi-thread 一问,
问个很基础的问题OpenGL能否方便实现自定义图形的移动,擦除和分层显示?
how to get time in milliseconds since 1970 (linux)新人5个包子请教问题,redhat读写文件的内存问题 (转载)
how to get time in milliseconds since 1970 on Linux问一个vim的问题
Python里边file writer的问题为什么redbox比netflix好用的多?
Java 8的streaminghelp understanding code (random number)
相关话题的讨论汇总
话题: shuffle话题: random
进入Programming版参与讨论
1 (共1页)
M7
发帖数: 219
1
这里有两个shuffle方法。第一个通过排序(乱序),第二个是标准的Fisher-Yates
shuffle, which has linear performance.
public static IEnumerable Shuffle(this IEnumerable
collection)
{
Random random = new Random();
return collection.OrderBy(item => random.Next());
}
public static IEnumerable FastShuffle(this IEnumerable
collection)
{
T[] buffer = collection.ToArray();
Random random = new Random();
for (int i = 0; i < buffer.Length; i++)
{
int j = random.Next(i, buffer.Length);
yield return buffer[j];
buffer[j] = buffer[i];
}
}
实验表明第一个Shuffle也非常快,和FastShuffle的差别非常小:
string array of size 50,000: shuffle, 1 milliseconds; fastshuffle, 2
milliseconds.
string array of size 5,000,000: shuffle, 1 milliseconds; fastshuffle, ~0
milliseconds.
时间是用Stopwatch获得的。
请问OrderBy里面是不是有特别的优化,如果是sort, 怎么会这么快?
h*******s
发帖数: 8454
2
这是c#还是java代码啊,看着像c#?
为啥不洗个1000次看平均时间,一次能说明问题么

【在 M7 的大作中提到】
: 这里有两个shuffle方法。第一个通过排序(乱序),第二个是标准的Fisher-Yates
: shuffle, which has linear performance.
: public static IEnumerable Shuffle(this IEnumerable
: collection)
: {
: Random random = new Random();
: return collection.OrderBy(item => random.Next());
: }
: public static IEnumerable FastShuffle(this IEnumerable
: collection)

M7
发帖数: 219
3
是C#. 我重复了很多次,给出结果是typical的。

【在 h*******s 的大作中提到】
: 这是c#还是java代码啊,看着像c#?
: 为啥不洗个1000次看平均时间,一次能说明问题么

t****t
发帖数: 6806
4
不是你挑typical的结果, 是你要拿1000次(或者1000000次)的总时间或者平均时间

【在 M7 的大作中提到】
: 是C#. 我重复了很多次,给出结果是typical的。
s***o
发帖数: 2191
5
Did you actually enumerate the result set? keep in mind that OrderBy is
implemented using deferred execution, which means it just returns a query
object that can be executed later to get the actual result (e.g. when you do
a foreach)
1 (共1页)
进入Programming版参与讨论
相关主题
help understanding code (random number)how to get time in milliseconds since 1970 (linux)
如何 测量某个函数的运行时间?how to get time in milliseconds since 1970 on Linux
how to get time() result in millisecond precision? (转载)Python里边file writer的问题
C++ 问题紧急求救Java 8的streaming
求问一道数组shuffle的问题 (转载)两行quicksort,不难些吧
一个搞统计的对C#的第一印象does the system guarantee this? (转载)
[合集] 面试问题multi-thread 一问,
问个很基础的问题OpenGL能否方便实现自定义图形的移动,擦除和分层显示?
相关话题的讨论汇总
话题: shuffle话题: random