测试结论:C 完胜 C++
测试代码:
#include <iostream>
#include <random>
#include <functional>
#include <chrono>
#include <thread>
#include <cstdlib>
#include <ctime>
using namespace std;
using namespace std::chrono;
class Rand {
public:
Rand(int l, int h):dist{l, h}{}
int get() {
return dist(gen);
}
private:
mt19937 gen{random_device{}()};
uniform_int_distribution<> dist;
};
class Crand {
public:
Crand(int lo, int hi):l(lo),h(hi){srand48_r(time(nullptr), &randBuffer);}
int get() const {
long ret;
lrand48_r((drand48_data *)(&randBuffer), &ret);
return ret%(h-l) + l;
}
private:
drand48_data randBuffer;
int l, h;
};
void randint(int l, int h) {
int a = 0;
Crand r{l, h};
//Rand r{l, h};
for (int i = 0; i < 1000000; ++i)
a = r.get();
}
int main() {
auto t1 = high_resolution_clock::now(

这篇博客通过对比测试发现,在多线程获取随机数的场景下,C语言的表现显著优于C++。详细测试代码揭示了性能差异的原因。
&spm=1001.2101.3001.5002&articleId=80037734&d=1&t=3&u=c65dc243208949f79685861d09f27813)
2578

被折叠的 条评论
为什么被折叠?



