Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1997. C# - nano 시간을 가져오는 방법 [링크 복사], [링크+제목 복사],
조회: 7027
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

C# - nano 시간을 가져오는 방법

윈도우에서 nano 시간을 어떻게 가져올 수 있을까요? 윈도우 환경의 Java에서 System.nanoTime을 호출해 보면,

public class Main {
    public static void main(String[] args) {
        long nanoTime1 = java.lang.System.nanoTime();
        long nanoTime2 = java.lang.System.nanoTime();
        long nanoTime3 = java.lang.System.nanoTime();
        long nanoTime4 = java.lang.System.nanoTime();
        long nanoTime5 = java.lang.System.nanoTime();

        System.out.println(nanoTime1);
        System.out.println(nanoTime2);
        System.out.println(nanoTime3);
        System.out.println(nanoTime4);
        System.out.println(nanoTime5);
    }
}

/* 출력 결과
1829807260513100
1829807260513200
1829807260513200
1829807260513300
1829807260513300
*/

빠르게 호출하다 보니 연이어 나오기도 하지만 무엇보다도 100 이하의 숫자는 0인 것이 특징입니다. 즉, 그 이하로는 값을 구할 수 없다는 것인데, nanoTime 메서드의 의미를 상기해 보면 결국 100나노초 이하의 값은 구할 수 없는 것입니다.

오호... 100나노초라... 익숙한 숫자죠? ^^ 바로 전에 언급했던 글에 그 이유가 있습니다.

Windows 10부터 바뀐 QueryPerformanceFrequency, QueryPerformanceCounter
; https://www.sysnet.pe.kr/2/0/13035

자, 그렇다면 닷넷에서는 어떻게 해야 할까요? 검색해 보면 다음의 글이 나옵니다.

What is the equivalent to System.nanoTime() in .NET?
; https://stackoverflow.com/questions/1551742/what-is-the-equivalent-to-system-nanotime-in-net

위의 답변에 보면 C# 코드가 나오는데요, 이를 이용해 위의 자바 예제처럼 닷넷 코드로 구성해 실행하면,

using System.Diagnostics;

internal class Program
{
    static void Main(string[] args)
    {
        long nano1 = Stopwatch.GetTimestamp() * 100L;
        long nano2 = Stopwatch.GetTimestamp() * 100L;
        long nano3 = Stopwatch.GetTimestamp() * 100L;
        long nano4 = Stopwatch.GetTimestamp() * 100L;
        long nano5 = Stopwatch.GetTimestamp() * 100L;

        Console.WriteLine(nano1);
        Console.WriteLine(nano2);
        Console.WriteLine(nano3);
        Console.WriteLine(nano4);
        Console.WriteLine(nano5);
    }
}
/* 출력 결과
1830258684212100
1830258684212100
1830258684212100
1830258684212200
1830258684212200
*/

위와 같이 나옵니다. 근래의 윈도우 운영체제에서 GetTimestamp 값은 QueryPerformanceCounter를 이용한 값과 동일한데요, 그래서 다음과 같은 식으로 구하는 것도 가능합니다.

using System;
using System.Runtime.InteropServices;

internal class Program
{
    [DllImport("Kernel32.dll")]
    static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

    static void Main(string[] args)
    {
        long time1 = 0;
        long time2 = 0;
        long time3 = 0;
        long time4 = 0;
        long time5 = 0;

        QueryPerformanceCounter(out time1);
        QueryPerformanceCounter(out time2);
        QueryPerformanceCounter(out time3);
        QueryPerformanceCounter(out time4);
        QueryPerformanceCounter(out time5);

        Console.WriteLine(time1 * 100L);
        Console.WriteLine(time2 * 100L);
        Console.WriteLine(time3 * 100L);
        Console.WriteLine(time4 * 100L);
        Console.WriteLine(time5 * 100L);
    }
}

/* 출력 결과
1830948394699000
1830948394699100
1830948394699100
1830948394699100
1830948394699200
*/

(지난 글에 설명한 이유로) 근래에는 QueryPerformanceFrequency 호출 없이도 다음과 같이 GetTimestamp로부터 단순히 10의 n 승에 해당하는 값만으로 다른 시간 단위로의 변환을 자유롭게 할 수 있습니다.

long time1 = Stopwatch.GetTimestamp();

long nanoSeconds = time1 * 100; // 나노초
long microSeonds = time1 / 10;  // 마이크로초
long milliSeconds = time1 / TimeSpan.TicksPerMillisecond; // 밀리초
long seconds = time1 / TimeSpan.TicksPerSecond; // 초




물론, 그 이상 정밀도를 높이려면 CPU에서 제공하는 tsc를 읽어내는 것도 한 방법입니다. 이전 글에서 설명한 대로,

윈도우 운영체제의 시간 함수 (4) - RTC, TSC, PM Clock, HPET Timer
; https://www.sysnet.pe.kr/2/0/11067#tsc

윈도우 운영체제의 시간 함수 (5) - TSC(Time Stamp Counter)와 QueryPerformanceCounter
; https://www.sysnet.pe.kr/2/0/11068

GHz 사이클 수에 따른 계산이므로, 만약 3.4GHz CPU라면 1 / 3,400,000,000 == 0.0000000002941...초가 나옵니다. 따라서 0.0000002941밀리초, 0.0002941마이크로초, 0.2941나노초가 되어 tsc 숫자 1이 변화하면 0.2941나노초가 지났다는 의미가 됩니다.

아쉽지만, 이 방법은 C#에서는 제공하는 방법이 없으므로 사용하려면 C로 DLL을 만들어 연결해야 합니다. (혹은, 간단한 기계어이므로 cpuid 방식처럼 만들어 호출하는 것은 가능합니다.)




참고로, Stopwatch의 도움말을 보면 이런 설명들이 나옵니다.

The timer used by the Stopwatch class depends on the system hardware and operating system. IsHighResolution is true if the Stopwatch timer is based on a high-resolution performance counter. Otherwise, IsHighResolution is false, which indicates that the Stopwatch timer is based on the system timer.


A pointer to a variable that receives the current performance-counter frequency, in counts per second. If the installed hardware doesn't support a high-resolution performance counter, this parameter can be zero (this will not occur on systems that run Windows XP or later).


On systems that run Windows XP or later, the function will always succeed and will thus never return zero.


그러니까, 이제는 그냥 무시해도 좋은 설명입니다. 즉, 현재는 (Windows XP 이후이므로) 대부분의 컴퓨터에서 Stopwatch.IsHighResolution의 값은 True가 반환될 것이며 따라서 DateTime.Ticks를 반환하는 경우는 없다고 봐도 좋을 것입니다.




그렇긴 한데, 여전히 좀 걸리는군요. 과연 Windows 10뿐만 아니라 현재의 Windows XP 이후의 모든 운영체제에서는 QueryPerformanceFrequency == 10,000,000 값이 고정적으로 나올까요? 혹시나 여러분들의 PC에서 다음의 소스 코드를 실행했을 때,

using System.Diagnostics;
using System.Runtime.InteropServices;

internal class Program
{
    [DllImport("Kernel32.dll")]
    static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

    [DllImport("Kernel32.dll")]
    static extern bool QueryPerformanceFrequency(out long ticksPerSecond);

    static void Main(string[] args)
    {
        QueryPerformanceFrequency(out long value);
        Console.WriteLine(value);

        {
            long nano1 = Stopwatch.GetTimestamp() * 100L;
            Console.WriteLine(nano1);
        }
        {

            long time1 = 0;
            QueryPerformanceCounter(out time1);
            Console.WriteLine(time1 * 100L);
        }
    }
}

/* 출력 결과
10000000
1838876675286800
1838876675452100
*/

저렇게 첫 번째 줄이 10000000 값이 아니거나, 또는 두 번째와 세 번째의 출력값이 현저하게 다른 경우가 있다면 제보 부탁드리겠습니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/4/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2022-04-26 06시04분
[kernel] 마지막예제에서 QueryPerformanceFrequency 호출 코드가 빠졌네요 ^^;
[guest]
2022-04-27 09시21분
@kernel ^^ 반영했습니다.
정성태

... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12101정성태1/5/202011106.NET Framework: 876. C# - PEB(Process Environment Block)를 통해 로드된 모듈 목록 열람
12100정성태1/3/20209130.NET Framework: 875. .NET 3.5 이하에서 IntPtr.Add 사용
12099정성태1/3/202011421디버깅 기술: 151. Windows 10 - Process Explorer로 확인한 Handle 정보를 windbg에서 조회 [1]
12098정성태1/2/202011020.NET Framework: 874. C# - 커널 구조체의 Offset 값을 하드 코딩하지 않고 사용하는 방법 [3]
12097정성태1/2/20209586디버깅 기술: 150. windbg - Wow64, x86, x64에서의 커널 구조체(예: TEB) 구조체 확인
12096정성태12/30/201911593디버깅 기술: 149. C# - DbgEng.dll을 이용한 간단한 디버거 제작 [1]
12095정성태12/27/201912946VC++: 135. C++ - string_view의 동작 방식
12094정성태12/26/201911100.NET Framework: 873. C# - 코드를 통해 PDB 심벌 파일 다운로드 방법
12093정성태12/26/201911138.NET Framework: 872. C# - 로딩된 Native DLL의 export 함수 목록 출력파일 다운로드1
12092정성태12/25/201910544디버깅 기술: 148. cdb.exe를 이용해 (ntdll.dll 등에 정의된) 커널 구조체 출력하는 방법
12091정성태12/25/201912077디버깅 기술: 147. pdb 파일을 다운로드하기 위한 symchk.exe 실행에 필요한 최소 파일 [1]
12090정성태12/24/201910714.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [1]파일 다운로드1
12089정성태12/23/201911443디버깅 기술: 146. gflags와 _CrtIsMemoryBlock을 이용한 Heap 메모리 손상 여부 체크
12088정성태12/23/201910418Linux: 28. Linux - 윈도우의 "Run as different user" 기능을 shell에서 실행하는 방법
12087정성태12/21/201910891디버깅 기술: 145. windbg/sos - Dictionary의 entries 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12086정성태12/20/201912913디버깅 기술: 144. windbg - Marshal.FreeHGlobal에서 발생한 덤프 분석 사례
12085정성태12/20/201910617오류 유형: 586. iisreset - The data is invalid. (2147942413, 8007000d) 오류 발생 - 두 번째 이야기 [1]
12084정성태12/19/201911266디버깅 기술: 143. windbg/sos - Hashtable의 buckets 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12083정성태12/17/201912528Linux: 27. linux - lldb를 이용한 .NET Core 응용 프로그램의 메모리 덤프 분석 방법 [2]
12082정성태12/17/201912402오류 유형: 585. lsof: WARNING: can't stat() fuse.gvfsd-fuse file system
12081정성태12/16/201914120개발 환경 구성: 465. 로컬 PC에서 개발 중인 ASP.NET Core 웹 응용 프로그램을 다른 PC에서도 접근하는 방법 [5]
12080정성태12/16/201912044.NET Framework: 870. C# - 프로세스의 모든 핸들을 열람
12079정성태12/13/201913253오류 유형: 584. 원격 데스크톱(rdp) 환경에서 다중 또는 고용량 파일 복사 시 "Unspecified error" 오류 발생
12078정성태12/13/201913200Linux: 26. .NET Core 응용 프로그램을 위한 메모리 덤프 방법 [3]
12077정성태12/13/201912703Linux: 25. 자주 실행할 명령어 또는 초기 환경을 "~/.bashrc" 파일에 등록
12076정성태12/12/201910932디버깅 기술: 142. Linux - lldb 환경에서 sos 확장 명령어를 이용한 닷넷 프로세스 디버깅 - 배포 방법에 따른 차이
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...