如何获取以毫秒为单位的经过时间? (视窗) [英] How to get the time elapsed in C in milliseconds? (Windows)

查看:125
本文介绍了如何获取以毫秒为单位的经过时间? (视窗)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Web上搜索了,但是我只找到了一种方法,但是通过这种方式,它返回的时间是几秒钟而不是毫秒.

I've searched in the Web but I've only found a way for do it, but in this way it returns in seconds instead of milliseconds.

我的代码是:

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

int main(void)
{
    int solucion;

    time_t start, stop;
    clock_t ticks;
    long count;

    time(&start);
    solucion = divisores_it(92000000, 2);
    time(&stop);

    printf("Finnished in %f seconds. \n", difftime(stop, start));
    return 0;
}

推荐答案

一种跨平台的方法是使用ftime.

A cross platform way is to use ftime.

此处是Windows的特定链接: http://msdn.microsoft.com/zh-CN/library/aa297926(v=vs.60).aspx

Windows specific link here: http://msdn.microsoft.com/en-us/library/aa297926(v=vs.60).aspx

下面的例子.

#include <stdio.h>
#include <sys\timeb.h> 

int main()     
{ 
    struct timeb start, end;
    int diff;
    int i = 0;
    ftime(&start);

    while(i++ < 999) {
        /* do something which takes some time */
        printf(".");    
    }

    ftime(&end);
    diff = (int) (1000.0 * (end.time - start.time)
        + (end.millitm - start.millitm));

    printf("\nOperation took %u milliseconds\n", diff);
    return 0;
}

我运行了上面的代码,并使用VS2008对其进行了跟踪,发现它实际上调用了Windows的GetSystemTimeAsFileTime函数.

I ran the code above and traced through it using VS2008 and saw it actually calls the windows GetSystemTimeAsFileTime function.

无论如何,ftime会给您毫秒级的精度.

Anyway, ftime will give you milliseconds precision.

这篇关于如何获取以毫秒为单位的经过时间? (视窗)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆