当前位置:首页 > 代码相关 > 正文内容

偶然想到的一个问题。。。

admin6年前 (2020-05-22)代码相关10522

今天突然想C#中,用数组中的Max()方法和直接通过比较获取最大值的时间谁快,于是试了试:

       static void Main(string[] args)
        {
            Random random = new Random();

            int[] arr = new int[100000000];
            int temp = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = random.Next();
            }


            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            int a = arr.Max();
            stopwatch.Stop();
            double t = stopwatch.Elapsed.TotalSeconds;

            stopwatch.Restart();
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] >= temp)
                {
                    temp = arr[i];
                }
            }
            stopwatch.Stop();
            double t2 = stopwatch.Elapsed.TotalSeconds;

            Console.WriteLine(a);
            Console.WriteLine(temp);
            Console.WriteLine("Max方法时间:" + t);
            Console.WriteLine("比较时间:" + t2);

            Console.ReadKey();
        }

结果是这样的:

image.png

看起来是比较快些。。。

扫描二维码推送至手机访问。

版权声明:本文由lovedm.club发布,如需转载请注明出处。

本文链接:https://lovedm.club/?id=50

分享给朋友:

“偶然想到的一个问题。。。” 的相关文章

递归计算1到x的和

递归真是个神奇的东西,当时学C的时候就没搞明白,学C#又遇到例子了。        public int SumXTo1(int x)     &n...

C#的类型系统

C#的类型系统

C#的五大数据类型:    类(Class)    结构体(Structures)    枚举(Enumerations)    接口(In...

C#事件_Sample_3

事件的拥有者同时是事件的响应者using System; using System.Windows.Forms; /// <summary> /// 事件的拥有者同时是事件的响应者 /// </summary> na...

C# 正则表达式(2)

// pattan = @"[^ahou]"; 表示匹配除ahou之外的字符,^在表示反义 string res4 = Regex.Replace(s, @"[^ahou]",&...

C# 与文件相关的几个类(3)

Path类,处理文件或路径的类,是一个静态类。方法:PathChangeExtension(String, String)更改路径字符串的扩展名。返回值为string。Combine(String, String)将两个字符串组合成一个路径。GetDirectoryName(String)返回指定路...