如何在C中以毫秒为单位获得程序的执行时间? [英] How can I get the execution time of a program in milliseconds in C?

查看:20
本文介绍了如何在C中以毫秒为单位获得程序的执行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我通过调用以获得我的程序的执行时间:

Currently I'm getting the execution wall time of my program in seconds by calling:

time_t startTime = time(NULL);
//section of code
time_t endTime = time(NULL);
double duration = difftime(endTime, startTime);

是否有可能以毫秒为单位获得墙时间?如果是这样怎么办?

Is it possible to get the wall time in milliseconds? If so how?

推荐答案

如果您使用的是 POSIX-ish 机器,请使用 gettimeofday() 代替;为您提供合理的便携性和微秒级分辨率.

If you're on a POSIX-ish machine, use gettimeofday() instead; that gives you reasonable portability and microsecond resolution.

稍微更深奥但也在 POSIX 中的是 clock_gettime() 函数,为您提供纳秒级分辨率.

Slightly more esoteric, but also in POSIX, is the clock_gettime() function, which gives you nanosecond resolution.

在许多系统上,您会发现一个函数 ftime() 实际上以秒和毫秒为单位返回时间.但是,它不再出现在 Single Unix Specification 中(与 POSIX 大致相同).您需要标题 :

On many systems, you will find a function ftime() that actually returns you the time in seconds and milliseconds. However, it is no longer in the Single Unix Specification (roughly the same as POSIX). You need the header <sys/timeb.h>:

struct timeb mt;
if (ftime(&mt) == 0)
{
     mt.time ... seconds
     mt.millitime ... milliseconds
}

这至少可以追溯到第 7 版(或第 7 版)Unix,因此它已被广泛使用.

This dates back to Version 7 (or 7th Edition) Unix at least, so it has been very widely available.

我在 times()clock() 的亚秒计时器代码中也有注释,它们再次使用其他结构和标题.我也有关于 Windows 使用 clock() 和每秒 1000 个时钟滴答(毫秒计时)的注释,以及一个旧的接口 GetTickCount() 在 Windows 95 上被注明为必要但不是在 NT 上.

I also have notes in my sub-second timer code on times() and clock(), which use other structures and headers again. I also have notes about Windows using clock() with 1000 clock ticks per second (millisecond timing), and an older interface GetTickCount() which is noted as necessary on Windows 95 but not on NT.

这篇关于如何在C中以毫秒为单位获得程序的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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