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

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

admin5年前 (2020-05-22)代码相关10208

今天突然想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://www.lovedm.club/?id=50

分享给朋友:

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

C# try-catch处理异常

使用try-catch进行异常处理,下面是两个小例子:两个例子中没有写finally语句finally的作用是无论有无异常,finally下的语句都会执行。//简单的处理异常namespace _20200323 {     class ...

九九乘法表算法

九九乘法表算法

namespace _20200324 {     class Program     {         st...

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...

C# 通过事件传递参数

C# 通过事件传递参数

20200622气死我了,一开始写的很详细,提交的时候因为长时间未操作提交失败了,今天懒得再写了,只把代码贴出来算了。事件发布相关类:public class ProEventArgs : EventArgs {    &nb...