Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1997. C# - nano 시간을 가져오는 방법 [링크 복사], [링크+제목 복사],
조회: 7307
글쓴 사람
정성태 (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)
11916정성태5/24/201912465Math: 51. MathNET + OxyPlot을 이용한 간단한 통계 정보 처리 - Histogram파일 다운로드1
11915정성태5/24/201914756Linux: 11. 리눅스의 환경 변수 관련 함수 정리 - putenv, setenv, unsetenv
11914정성태5/24/201914458Linux: 10. 윈도우의 GetTickCount와 리눅스의 clock_gettime파일 다운로드1
11913정성태5/23/201912086.NET Framework: 838. C# - 숫자형 타입의 bit(2진) 문자열, 16진수 문자열 구하는 방법파일 다운로드1
11912정성태5/23/201911756VS.NET IDE: 137. Visual Studio 2019 버전 16.1부터 리눅스 C/C++ 프로젝트에 추가된 WSL 지원
11911정성태5/23/201910828VS.NET IDE: 136. Visual Studio 2019 - 리눅스 C/C++ 프로젝트에 인텔리센스가 동작하지 않는 경우
11910정성태5/23/201919469Math: 50. C# - MathNet.Numerics의 Matrix(행렬) 연산 [1]파일 다운로드1
11909정성태5/22/201913902.NET Framework: 837. C# - PLplot 사용 예제 [1]파일 다운로드1
11908정성태5/22/201912293.NET Framework: 836. C# - Python range 함수 구현파일 다운로드1
11907정성태5/22/201910086오류 유형: 541. msbuild - MSB4024 The imported project file "...targets" could not be loaded
11906정성태5/21/201910026.NET Framework: 835. .NET Core/C# - 리눅스 syslog에 로그 남기는 방법
11905정성태5/21/201910680.NET Framework: 834. C# - 폴더 경로 문자열에서 "..", "." 표기를 고려한 최종 문자열을 얻는 방법 - 두 번째 이야기
11904정성태5/21/201916918.NET Framework: 833. C# - Open Hardware Monitor를 이용한 CPU 온도 정보 [1]파일 다운로드1
11903정성태5/21/201911907오류 유형: 540. .NET Core - System.PlatformNotSupportedException: The named version of this synchronization primitive is not supported on this platform.
11902정성태5/21/201911066오류 유형: 539. mstest 실행 시 "The directory name is invalid." 오류 발생
11901정성태5/21/201912189오류 유형: 538. msbuild 오류 - Could not find a part of the path '%LOCALAPPDATA%\Temp\2\.NETFramework,Version=v4.0.AssemblyAttributes.cs'
11900정성태5/18/201911479오류 유형: 537. "sfc /scannow" 실행 중 시스템이 부팅되는 현상
11899정성태5/17/201912500Linux: 9. Linux에서 윈도우의 OutputDebugString 대신 사용할 수 있는 syslog [1]
11898정성태5/16/201913884VC++: 130. C++ string의 c_str과 data 함수의 차이점 [3]
11897정성태5/16/201920535오류 유형: 536. Visual Studio - "Developer Pack"을 설치했는데도 "대상 프레임워크" 목록에 나오지 않는 경우 [2]
11896정성태5/15/201915275개발 환경 구성: 440. C#, C++ - double의 Infinity, NaN 표현 방식파일 다운로드1
11895정성태5/12/201913637.NET Framework: 832. ML.NET Model Builder - 회귀(Regression), 다중 분류(Multi-class classification) 예제파일 다운로드1
11894정성태5/10/201914786VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [5]
11893정성태5/10/201912424오류 유형: 535. C# 6.0 이상의 문법을 컴파일 시 오류가 발생한다면?
11892정성태5/10/201912465웹: 38. HTTP Cookie의 expires 시간 형식(RFC7231)
11891정성태5/9/201914967.NET Framework: 831. (번역글) .NET Internals Cookbook Part 12 - Memory structure, attributes, handles
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...