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

Why are the loops for memset() 1M times and 10M times cost the same time?

本文关键字:时间 10M 次和 memset 循环 1M 为什么      更新时间:2023-10-16

这是我的代码:

#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 中完成