C#【必备技能篇】精确计时(延时)的方法

您所在的位置:网站首页 c语言一毫秒的延时程序是什么 C#【必备技能篇】精确计时(延时)的方法

C#【必备技能篇】精确计时(延时)的方法

2024-06-22 07:34| 来源: 网络整理| 查看: 265

文章目录 1、调用WIN API中的GetTickCount【误差:15ms左右】用法:延时函数测试【单位:毫秒】: 2、调用WIN API中的timeGetTime【推荐】用法:延时函数测试【单位:毫秒】: 3、调用.net自带的方法System.Environment.TickCount用法:延时函数测试【单位:毫秒】: 4、调用WIN API中的QueryPerformanceCounter用法:延时函数测试【单位:毫秒(也可以延时微秒)】: 5、使用.net的System.Diagnostics.Stopwatch类【推荐】用法:测试延时函数【单位:毫秒(也可以延时微妙)】: 6、使用.net的DateTime.Ticks类【不推荐,延时效果很差】延时函数测试【单位:微秒Microseconds】: 参考:

在Visual Studio写代码时的提示: 在这里插入图片描述

综合网上的一些文章,精确计时主要有以下几种方式:

1、调用WIN API中的GetTickCount【误差:15ms左右】 [DllImport("kernel32")] static extern uint GetTickCount();

从操作系统启动到现在所经过的毫秒数,精度为1毫秒,经简单测试发现其实误差在大约在15ms左右 缺点:返回值是uint,最大值是2的32次方,因此如果服务器连续开机大约49.71天以后,该方法取得的返回值会归零。

用法: uint s1 = GetTickCount(); Thread.Sleep(2719); Console.WriteLine(GetTickCount() - s1); //单位毫秒 延时函数测试【单位:毫秒】: using System; using System.Runtime.InteropServices; public class Example { [DllImport("kernel32")] static extern uint GetTickCount(); public static void Main() { Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff")); delay_ms(10); Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff")); Console.ReadLine(); } public static void delay_ms(uint delay_time) { uint time_start = GetTickCount(); uint time_stamp = 0; do { time_stamp = GetTickCount() - time_start; } while (time_stamp


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3