软件用于Windows操作系统的C中断服务程序

#include  #include  #include  void Task() { printf("Hi"); } int main ( ) { time_t t; clock_t start, end; long i; long count; double x = 0.0; count = 2; start = clock(); time(&t); printf(ctime(&t)); printf( "Counting to %ld\n", count ); if(count) { Task(); } end = clock(); printf( "That took %f seconds and I counted up to %ld", (((double)(end-start)/CLOCKS_PER_SEC)), count ); printf( "\nThat also took %d clock tics\n ", clock()); return 0; } 

我想获得执行Task函数所需的开始时间和结束时间。 我试图为任务function创建中断,但在程序中显示Hi。 我没有成功。 所以,任何人都可以为此指导我。

尝试从多媒体计时器开始 。 另一种可能的方法可能是使用CreateTimerQueueTimer()和朋友 。

在用户模式下无法进行中断,只有内核模式驱动程序可以为中断请求提供服务。

但是,您可以定期使用OS调用的回调函数。 在Windows上,您可以使用多媒体时间(但微软宣称已过时)或计时器队列计时器来实现此目的(例如:检查此项: http : //msdn.microsoft.com/en-us/library/windows/desktop/ms682485% 28v = vs.85%29.aspx )。

这是我编写的一个旧的测试程序,它使用多媒体计时器(过时但它们仍适用于最近的Windows版本……):

 #include  #include  volatile long timer = 0; // Will be called every 1 ms void CALLBACK timer_func(UINT uTimerID, UINT uMsg, DWORD *dwUser, DWORD *dw1, DWORD *dw2) { timer++; } int main(int argc, char *argv[]) { MMRESULT id = timeSetEvent(1, 0, (LPTIMECALLBACK) timer_func, NULL, TIME_PERIODIC); printf("Waiting 10 seconds... "); fflush(stdout); Sleep(10000); printf("ok. Timer = %ld.\n", timer); timeKillEvent(id); return 0; } 

如果您只想精确测量函数调用的持续时间,只需使用QueryPerformanceCounter()和QueryPerformanceFrequency():

 #include  #include  void task() { // do something... } int main() { LARGE_INTEGER start, stop, freq; QueryPerformanceCounter(&start); task(); QueryPerformanceCounter(&stop); QueryPerformanceFrequency(&freq); double time_len = (stop.QuadPart - start.QuadPart) / (double) freq.QuadPart; printf("Task length: %0.8f seconds.\n", time_len); } 

讨论后的新答案(请参阅我之前回答的评论):您可以通过以下方式实现与GetStopWatch()函数等效的函数:

 #include  #include  #include  // assuming we return times with microsecond resolution #define STOPWATCH_TICKS_PER_US 1 uint64_t GetStopWatch() { LARGE_INTEGER t, freq; uint64_t val; QueryPerformanceCounter(&t); QueryPerformanceFrequency(&freq); return (uint64_t) (t.QuadPart / (double) freq.QuadPart * 1000000); } void task() { // do something... } int main() { uint64_t start = GetStopWatch(); task(); uint64_t stop = GetStopWatch(); printf("Elapsed time (microseconds): %lld\n", stop - start); } 

希望这可以帮助。