Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1997. C# - nano 시간을 가져오는 방법 [링크 복사], [링크+제목 복사],
조회: 7284
글쓴 사람
정성태 (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 ^^ 반영했습니다.
정성태

... 31  [32]  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12844정성태10/3/20216381오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/20216842스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202125392오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/20218746스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/20218837.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/20219896.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/20219469.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/20218421VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/20218045Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/20219270.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/20217680오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/20217112VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/20218038VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/20216535VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/20218851오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
12829정성태9/5/202110419.NET Framework: 1115. C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능파일 다운로드1
12828정성태9/4/20218557.NET Framework: 1114. C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언파일 다운로드1
12827정성태9/4/20218472스크립트: 27. 파이썬 - 웹 페이지 데이터 수집을 위한 scrapy Crawler 사용법 요약
12826정성태9/3/202110682.NET Framework: 1113. C# 10 - (12) 문자열 보간 성능 개선 [1]파일 다운로드1
12825정성태9/3/20218285개발 환경 구성: 603. GoLand - WSL 환경과 연동
12824정성태9/2/202117381오류 유형: 760. 파이썬 tensorflow - Dst tensor is not initialized. 오류 메시지
12823정성태9/2/20216989스크립트: 26. 파이썬 - PyCharm을 이용한 fork 디버그 방법
12822정성태9/1/202112224오류 유형: 759. 파이썬 tensorflow - ValueError: Shapes (...) and (...) are incompatible [2]
12821정성태9/1/20217838.NET Framework: 1112. C# - .NET 6부터 공개된 ISpanFormattable 사용법
12820정성태9/1/20218103VC++: 147. Golang - try/catch에 대응하는 panic/recover [1]파일 다운로드1
12819정성태8/31/20218236.NET Framework: 1111. C# - FormattableString 타입
... 31  [32]  33  34  35  36  37  38  39  40  41  42  43  44  45  ...