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

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

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

今天突然想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

分享给朋友:

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

C#的类型系统

C#的类型系统

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

C# 中左移运算

C# 中左移运算

将一个数换算成二进制,整体向左移动指定的位数。如:7的二进制在Int32中二进制表达为:00000000 00000000 00000000 00000111将其左移一位则变为:00000000 00000000 00000000 00001110若移位后超出最大位数,则超出部分舍掉,如:Int32...

C# Lambda表达式

简单用法,一句一句来,便于理解 Func<int, int, int> func = new Func<int, int, int>((int a, int b) => { return a * b; });(int a, int b) => { ret...

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

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

C# 与文件访问相关的常用的类:File类、Directory类、Path类、FileInfo类、DirectoryInfo类、FileSystemInfo类、FileSystemWatcher类以上几个类均在System.IO命名空间下。挨个说吧:File类:静态类,只有静态方法,用于移...

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

Directory类:静态类,主要处理文件目录。方法:CreateDirectory(String)在指定路径中创建所有目录和子目录,除非它们已经存在。返回值是一个DirectoryInfo对象Delete(String)从指定路径删除空目录。无返回值。Exists(String)确定给定路径是否引...

PIE二次开发 加载栅格数据

1、获得栅格数据集路径2、打开栅格数据集3、创建栅格图层4、将数据添加到图层并刷新要添加两个引用:using PIE.DataSource;using PIE.Carto;// 获得要打开栅格数据的路径 OpenFileDialog file = new&n...