C++版的实现方式可以写成这样:
int64_t inline getTimeInMicroseconds() {
struct timeval tp;
::gettimeofday(&tp, NULL);
return tp.tv_sec * 1000000 + tp.tv_usec;
}
其中,timeval的定义是在C++库,路径是/usr/include/x86_64-linux-gnu/bits/types/struct_timeval.h中,定义如下:
#ifndef __timeval_defined
#define __timeval_defined 1
#include <bits/types.h>
/* A time value that is accurate to the nearest
microsecond but also has a range of years. */
struct timeval
{
__time_t tv_sec; /* Seconds. */
__suseconds_t tv_usec; /* Microseconds. */
};
#endif
gettimeofday是boost库中的函数,路径是/usr/include/boost/config/platform/vxworks.hpp,定义是:
inline int gettimeofday(struct timeval *tv, void * /*tzv*/) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
tv->tv_sec = ts.tv_sec;
tv->tv_usec = ts.tv_nsec / 1000;
return 0;
}
#endif
python版可以根据time.time()计算,但是不确定精确度是否足够,在stackoverflow中有这个问题的python版解法,用到了python的ctypes库,底层和C++版很接近了。
先定义一个GS_timing.py文件,在里面定义相关函数。
"""
GS_timing.py
-create some low-level Arduino-like millis() (milliseconds) and micros()
(microseconds) timing functions