为什么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 中完成
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 从持续时间构造std::chrono::system_clock::time_point
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 使用简单类型列表实现的指数编译时间.为什么
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在已经使用Git的情况下减少编译时间
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 从文本文件中读取时钟时间和事件时间并进行处理
- 具有未知值时的时间复杂性
- 如何减少花费的时间
- C++在变量给定的指定时间内关闭电脑
- rcpp函数中的清理时间很长
- C++:floor unix时间戳到UTC月份
- 如何在c++中录制具有精确帧时间戳的视频
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- KMP算法和LPS表构造的运行时间
- 为什么std::互斥需要很长的、非常不规则的时间来共享
- 为什么memset()的循环1M次和10M次花费相同的时间