0
#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。我没有成功。所以你能请任何人都可以指导我这件事。

4

3 回答 3

1

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

于 2013-11-04T15:43:55.143 回答
0

在用户模式下没有办法产生中断,只有内核模式驱动程序才能服务中断请求。

但是,您可以让操作系统定期调用回调函数。在 Windows 上,您可以使用多媒体时间(但 Microsoft 宣布已过时)或计时器队列计时器(例如: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);
}
于 2013-11-04T15:44:56.457 回答
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);
}

希望这可以帮助。

于 2013-11-06T21:00:35.280 回答