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

时间:2013-11-04 15:36:30

标签: c timer operating-system interrupt clock

#include <stdio.h>
#include <time.h>
#include <windows.h>

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函数所需的开始时间和结束时间。我正在尝试为任务函数创建中断但在程序中显示Hi。我没有成功。所以,任何人都可以指导我这件事。

3 个答案:

答案 0 :(得分:1)

尝试从Multimedia Timers开始。另一种可能的方法可能是使用CreateTimerQueueTimer() and friends

答案 1 :(得分:0)

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

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

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

#include <stdio.h>
#include <windows.h>

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 <windows.h>
#include <stdio.h>

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);
}

答案 2 :(得分:0)

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

#include <windows.h>
#include <stdio.h>
#include <stdint.h>

// 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);
}

希望这有帮助。