加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 是否有时间函数,其结果保证每次调用都会改变?

发布时间:2020-12-16 10:44:14 所属栏目:百科 来源:网络整理
导读:在我尝试这个之前,我认为它是GetTickCount64(): #include fstream#include windows.h#include iostreamvoid doSomething();int main() {srand(GetTickCount64());std::fstream file;file.open("test.dat",std::ios_base::out | std::ios_base::trunc); for
在我尝试这个之前,我认为它是GetTickCount64():

#include <fstream>
#include <windows.h>
#include <iostream>

void doSomething();

int main() {
srand(GetTickCount64());
std::fstream file;
file.open("test.dat",std::ios_base::out | std::ios_base::trunc);

    for (;;)
        file <<std::boolalpha<<(GetTickCount64()==GetTickCount64()) << std::endl;
}

还有这个:

#include <fstream>
#include <windows.h>
#include <iostream>

void doSomething();

int main() {
srand(GetTickCount64());
std::fstream file;
file.open("test.dat",std::ios_base::out | std::ios_base::trunc);

__int64 a,b;
for (;;) {
    a = GetTickCount64();
    doSomething();
    b = GetTickCount64();
    file <<std::boolalpha<<(a==b) << std::endl;
    }
}

void doSomething() {
int T=(see below);
    for (int i = 0; i < (rand() % T); i++)
        __noop;
}

对于第一个变体,我每200.000真(806642次迭代)收到1假.

对于第二个变量并且T = 5,每90000真(627018次迭代)我收到1假,其中T = 1000,每4444真(693361次迭代)我收到1假.

因此,每次调用时绝对不会给出不同的值.我需要在共享内存区域中创建一个时间戳,我尝试猜测程序无法正常工作时有很多乐趣!

我可以使用什么功能呢?
?谢谢!

编辑澄清:我明白计时器根本不能具有无限的准确性,但我想知道是否存在一个准确到足以比cpu更快的计时器(是的,可能这是一个荒谬的问题,但我只是模糊不清关于定时器如何工作的想法).

顺便说一下,我会使用一些随机函数来生成一个唯一的数字,然后我会将时间存储在另一个地方.

解决方法

既然你只关心单调增加的价值,并且(显然)不关心一个和另一个之间存在多大差异,那么 InterlockedIncrement64似乎对你有用.

从那里可以确保所有需要序列号的代码都可以访问同一位置. Windows有几种方法可以做到这一点,但你还没有真正告诉我们你正在做什么/如何使用它来提供有关哪种最适合你的需求的有意义的建议.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读