-->

microtime中()等效的C和C ++?(Microtime() Equivalent for

2019-07-30 13:13发布

我想知道是否有一个等同于PHP函数microtime中()中的C C ++。 我环顾四周,但没有找到一个明确的答案。

谢谢!

Answer 1:

在Linux上,你可以使用gettimeofday的 ,这应该给了相同的信息。 事实上,我认为是PHP底层使用的功能。



Answer 2:

没有完全等效于PHP的microtime中(),但你可以用基于下面的代码类似功能的函数:

Mac OS X和也可能的Linux / Unix

#include <sys/time.h>
struct timeval time;
gettimeofday(&time, NULL); #This actually returns a struct that has microsecond precision.
long microsec = ((unsigned long long)time.tv_sec * 1000000) + time.tv_usec;

(基于: http://brian.pontarelli.com/2009/01/05/getting-the-current-system-time-in-milliseconds-with-c/ )


视窗:

unsigned __int64 freq;
QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
double timerFrequency = (1.0/freq);

unsigned __int64 startTime;
QueryPerformanceCounter((LARGE_INTEGER *)&startTime);

//do something...

unsigned __int64 endTime;
QueryPerformanceCounter((LARGE_INTEGER *)&endTime);
double timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency);

(由Darcara回答,来自: https://stackoverflow.com/a/4568649/330067 )



Answer 3:

C ++ 11增加了一些标准的计时功能(见20.11“时间公用事业”)具有良好的精度,但大多数编译器不支持这些呢。

主要是你需要使用您的操作系统的API,如gettimeofday对POSIX。



Answer 4:

用于定时的码部分中,尝试的std ::时钟 ,它返回蜱,然后通过除以CLOCKS_PER_SEC



Answer 5:

libUTP(uTorrent的传输协议库)具有良好的例子上得到不同的平台上microtime中。



Answer 6:

在C ++ 11我相信等价于PHP中的microtime(true)是:

#include <chrono>
double microtime(){
    return (double(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count()) / double(1000000));
}
  • 但我不知道该等价的C是什么,或者甚至有一个(正如其他人所指出的那样,gettimeofday的是POSIX的一部分,但不是C / C ++规范的一部分)

有趣的是一微秒是百万分之一秒,但C ++还支持纳秒,这是一秒钟的十亿分之一,我想你会得到更高的精度std::chrono::nanoseconds ,而不是std::chrono::microseconds ,但在这一点上你可能会碰到的最大数量的限制double和函数的名称会被误导(这样的功能应该有名称nanotime()microtime()并返回可能应该超过一倍更大的东西) ,顺便说一句我有集合PHP-功能-移植到C ++这里: https://github.com/divinity76/phpcpp (和microtime中()是其中)



文章来源: Microtime() Equivalent for C and C++?
标签: c++ c microtime