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

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

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

今天突然想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# 使用不安全的代码

首先需要在 项目->属性->生成 中勾选允许不安全代码下面的代码使用了指针,通过指针修改结构体的成员namespace _20200320 {     class Program   &nbs...

九九乘法表算法

九九乘法表算法

namespace _20200324 {     class Program     {         st...

C# 正则表达式(1)

C# 正则表达式(1)

用于匹配输入文本的模式string s = "this is a test!"; string res = Regex.Replace(s, "^",&nbs...

C# 正则表达式(2)

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

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

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

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

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

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