gpt4 book ai didi

c++ - 为什么 memset() 循环 1M 次和 10M 次花费相同的时间?

转载 作者:行者123 更新时间:2023-11-28 00:09:00 26 4
gpt4 key购买 nike

这是我的代码:

#include <iostream>
#include <sys/time.h>
#include <string.h>

using namespace std;

int main()
{
char* a = (char*)malloc(1024);
int times = 10000000;
struct timeval begin, end;
gettimeofday(&begin, NULL);
for(int i=0; i<times; i++){
memset(a, 1, 1024);
}
gettimeofday(&end, NULL);
cout << end.tv_sec - begin.tv_sec << "." << end.tv_usec - begin.tv_usec << endl;
return 0;
}

当我将时间设置为 1M 时,输出约为 0.13 秒,但是当我将时间设置为 10M 时,输出仍约为 0.13 秒。是什么原因造成这种情况?是Linux的优化还是编译器的问题?

最佳答案

更新:优化已禁用

我认为您需要使用更精确的 chrono 而不是 time.h 并禁用编译器优化:

#include <iostream>
#include <string.h>
#include <chrono>

#ifdef __GNUC__
#ifdef __clang__
static void test() __attribute__ ((optnone)) {
#else
static void __attribute__((optimize("O0"))) test() {
#endif
#elif _MSC_VER
#pragma optimize( "", off )
static void test() {
#else
#warning Unknow compiler!
static void test() {
#endif

char* a = (char*) malloc(1024);

auto start = std::chrono::steady_clock::now();
for(uint64_t i = 0; i < 1000000; i++){
memset(a, 1, 1024);
}
std::cout<<"Finished in "<<std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count()<<std::endl;
}

#ifdef _MSC_VER
#pragma optimize("", on)
#endif

int main() {
test();

return 0;
}

10M:完成于 259.8511M:完成于 26.3928

关于c++ - 为什么 memset() 循环 1M 次和 10M 次花费相同的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34039316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com