任何时间函数保证为调用返回不同的值
Any Time Function Guarantee to Return Different Values for Calls
我正在寻找一个时间函数,它保证为不同的调用返回不同的值。我在 LINUX 上尝试了以下方法,只是发现它不是我想要的,它可能会为来自不同线程的调用返回相同的值。
long GetTickCount()
{
struct timespec now;
clock_gettime(MONOTONIC, &now);
return now.tv_sec * 1000000000LL + now.tv_nsec;
}
在 Linux 上还有其他方法可以做到这一点吗?
任何时钟的粒度都有限,这可能会导致连续调用返回相同的值。 为了解决这个问题,您需要使用全局计数器:
static long long previous_time = 0;
long long get_strictly_monotonic_time() {
int rc;
struct timespec tp;
long long t;
rc = clock_gettime(CLOCK_MONOTONIC, &tp);
if(rc < 0) return -1;
t = tp.tv_sec * 1000000000LL + tp.tv_nsec;
/* Critical region */
if(t <= previous_time)
t = previous_time + 1;
previous_time = t;
/* End of critical region */
return t;
}
由于您希望这在多个线程中是可靠的,因此您需要使用全局互斥锁(上面带有"关键区域"注释的区域)保护全局计数器。
相关文章:
- 从python中调用C++函数并获取返回值
- 返回递归调用和仅递归调用的区别
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 调用CreateProcess()并获取字符串的返回值
- 使用JsonCpp将数据返回到带有pybind11的python会在python调用中产生Symbol not foun
- 将错误返回给调用方而不是立即在 C++ 中抛出错误是否是一种好的做法
- 返回指向对象的指针的函数调用是否为 prvalue?
- 如何安全地从 DLL 调用返回对象
- getopt_long_only第二次调用时返回 -1
- 如何构造可以调用和返回两种不同类型的模板
- 从返回 std::optional of std::vector 的函数中获取结果到调用方
- C++如何使函数返回调用它的对象
- 谷歌嘲笑!我的测试出错.默认情况下,呼叫将返回调用
- 仅使用有关类型而不是对象的信息返回调用的类型
- 从C#返回调用C++dll函数的值时发生访问冲突
- 问题5.3:访问/返回/调用动态创建的复选框(?)
- 按值返回调用复制构造函数或复制赋值运算符
- Tcl_Eval在出错时返回调用堆栈
- 按值返回调用复制构造函数
- 为什么在没有显式返回语句的情况下,递归返回调用会跳出堆栈