为什么 memset() 循环 1M 次和 10M 次花费相同的时间?
Why are the loops for memset() 1M times and 10M times cost the same time?
这是我的代码:
#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.851
1M:完成于 26.3928
这是我的代码:
#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.851 1M:完成于 26.3928