• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
风拂晚柳
博客园    首页    新随笔    联系   管理    订阅  订阅

C#-----计算程序运行时间

1.DateTime类

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            long sum = 0;
            DateTime beforDT = System.DateTime.Now;
            for (int i = 0; i < 10000000; i++)
            {
                sum += i;
            }
            DateTime afterDT = System.DateTime.Now;
            TimeSpan ts = afterDT.Subtract(beforDT);
            Console.WriteLine("DateTime总共花费{0}ms.", ts.TotalMilliseconds);
            Console.ReadLine();
        }
    }
}

2.Stopwatch类

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            long sum = 0;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 10000000; i++)
            {
                sum += i;
            }
            sw.Stop();
            TimeSpan timeSpan = sw.Elapsed;
            Console.WriteLine("Stopwatch总共花费{0}ms.", timeSpan.TotalMilliseconds);
            Console.ReadLine();
        }
    }
}

 

posted @ 2019-07-19 10:57  风拂晚柳  阅读(191)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3