WinAPI QueryPerformanceCounter 함수와 Stopwatch 클래스를 이용해 두가지 버젼으로 구현하였다.

 

 

 

 

usSleep.zip

 

 

 

 

QueryPerformanceCounter를 이용한 us Sleep

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;
 
namespace Some
{
    public class Sleep
    {
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
 
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(out long lpFrequency);
 
        private static long freq;
        private static double ufreq;
        private static double mfreq;
 
        static Sleep()
        {
            if (QueryPerformanceFrequency(out freq) == false)
            {
                throw new Win32Exception();
            }
            ufreq = freq / 1000000;
            mfreq = freq / 1000;
        }
 
        public Sleep()
        {
            USleep(0);
        }
 
        public void USleep(double us)
        {
            long startTime = 0;
            long nowTime = 0;
 
            QueryPerformanceCounter(out startTime);
 
            while (((nowTime - startTime) / ufreq) < us)
            {
                QueryPerformanceCounter(out nowTime);
            }
        }
 
        public void MSleep(double ms)
        {
            long startTime = 0;
            long nowTime = 0;
 
            QueryPerformanceCounter(out startTime);
 
            while (((nowTime - startTime) / mfreq) < ms)
            {
                QueryPerformanceCounter(out nowTime);
            }
        }
    }
}

 

 

 

 

 

Stopwatch Class를 이용한 us Sleep

 

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
 
namespace Some
{
    class SWSleep
    {
        long freq = 0;
        public SWSleep()
        {
            this.freq = Stopwatch.Frequency;
            USleep(0);
        }
 
        internal void USleep(int us)
        {
            double sec = (double)us / 1000000;
            Stopwatch sw = Stopwatch.StartNew();
            while (sw.ElapsedTicks / (double)freq < sec)
            {
            }
        }
 
        internal void MSleep(int ms)
        {
            double sec = (double)ms / 1000;
            Stopwatch sw = Stopwatch.StartNew();
            while (sw.ElapsedTicks / (double)freq < sec)
            {
            }
        }
    }
}

 

+ Recent posts