这个代码获得系统时间,通过计算差值得到程序运行的时间。
然后通过加入延时和循环,可以监视每次循环经历的时间。最后得到整个代码运行时间。
用到了系统时间,毫秒和秒
以及延时函数
两种类型,扫描时间和系统时间
using System;
using System.Threading;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;class Program
{static void Main(string[] args){DateTime startime=DateTime.Now;DateTime endime=DateTime.Now;TimeSpan duration = endime - startime;for(int i = 0;i<10;i++){Console.Write(duration.Seconds);Console.WriteLine("\t"+duration.Milliseconds);Thread.Sleep(1000);endime = DateTime.Now;duration = endime - startime;}Console.WriteLine(duration.Seconds + "秒" + duration.Milliseconds + "毫秒");}
}
输出结果:
0 2
1 18
2 34
3 51
4 60
5 63
6 72
7 86
8 94
9 96
10秒99毫秒
简单的一分钟定时:
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace 练习
{class Program{static void Main(string[] args){DateTime startime = DateTime.Now;DateTime endime = DateTime.Now;TimeSpan duration = endime - startime;int i = 1;while (true){//Console.Write(duration.Seconds);//Console.WriteLine("\t" + duration.Milliseconds);Thread.Sleep(1000);endime = DateTime.Now;duration = endime - startime;Console.WriteLine(duration.Seconds); Console.WriteLine(duration.Minutes);if (duration.Minutes == 1){break;}}Console.WriteLine(duration.Seconds + "秒" + duration.Milliseconds + "毫秒");}}
}