2009-12-22 28 views
2

我需要使用QueryPerformanceCounter Win32 API格式化一天的时间。 格式为:HH:mm:ss.ffffff,包含小时minut秒和微秒。 我需要使用THIS函数,因为另一个进程(用C编写)正在使用此函数,目的是在两个地方使用相同的函数。.NET QueryPerformanceCounter打印白天时间

感谢

回答

0

可以使用: 1)System.Diagnostics.Stopwatch类使用QueryPerformanceCounter(),使您不必进行P/Invoke。 2)可以直接使用从Win32 dll导入。 [DLLImport(Win32)]和函数的名称

2

你不应该使用QueryPerformanceCounter来确定每天的时间。它只能用于确定具有非常高分辨率的已用时间间隔,因为它会返回自上次重新启动计算机以来所经过的滴答数。

这样,在最好的,你可能只确定自QueryPerformanceCounter以前读书,绝不能发生过去太久多少小时,分钟和秒过去了。

为了从蜱转换成你需要确定(使用QueryPerformanceFrequency)计算机上的蜱你正在运行的QueryPerformanceCounter函数,然后通过该频率将您的阅读频率秒:

// obtain frequency 
long freq; 
QueryPerformanceFrequency(freq); 

// then obtain your first reading 
long start_count; 
long end_count; 
QueryPerformanceCounter(start_count) 

// .. do some work 

// obatin your second reading 
QueryPerformanceCounter(end_count); 

// calculate time elapsed 
long milliseconds_elapsed = (long)(((double)(end_count - start_count)/freq) * 1000); 

// from here on you can format milliseconds_elapsed any way you need to 

上述示例另一种方法是使用在.net可用TimeSpan结构,其具有一个构造函数蜱像这样:

// then obtain your first reading 
long start_count; 
long end_count; 
QueryPerformanceCounter(start_count) 

// .. do some work 

// obatin your second reading 
QueryPerformanceCounter(end_count); 

TimeSpan time_elapsed = new TimeSpan(end_count - start_count); 

Console.WriteLine("Time Elapsed: " + time_elapsed.ToString()); 
+0

-1根本不回答问题。 OP表示他*必须*使用该功能。由于其他原因,我有完全相同的问题。我使用所描述的方法测量自年龄以来的间隔,但这与OP(和我的)问题/问题完全无关。 – zerm

+0

(+1)不像其他人那样,我的-1也明显地理解了与我所做的不同的问题。请参阅我的回答,了解我的理解以及我的解决方案。 – zerm

5

的System.Diagnostics.Stopwatch类使用QueryPerformanceCounter(),使您不必进行P/Invoke。

0

可能我误解了这个问题,因为以前的答案都没有任何相关性。

我有问题(这把我送进这里):鉴于从QueryPerformanceCounter的值,因为有些东西在我的掌握使用该函数指定时间戳,我怎么可以将这些值转换成一个正常的日期/时间?

我想,QueryPerformanceCounter返回,因为系统依赖于QueryPerformanceFrequency引导,乘以(并在第延长)的秒数。 因此,最简单的解决方案是获取当前日期/时间,减去QueryPerformanceCounter/QueryPerformanceFrequency返回的秒数,然后添加您想要格式化为一天中的值。