在C中,我将循环执行总数减少了近3倍,但是通过测试执行时间,我发现这样做几乎没有任何改进。所有优化级别均已测试,结果基本相同(包括O0、O1、O2和O3)。我猜它\xe2\x80\x99是编译器的问题,但我想知道是什么原因导致这种情况。以及如何做才能使结果达到预期。
\n代码如下:
\n#include <stdio.h>\n#include <time.h>\n#include <stdlib.h>\n\n#define Len 10000000\n\n// Two variables that count the number of loops\nint count1 = 0;\nint count2 = 0;\n\nint main(int argc, const char * argv[]) {\n srandom((unsigned)time(NULL));\n \n // An array to increase the index,\n // the range of its elements is 1-256\n int rand_arr[128];\n for (int i = 0; i < 128; ++i)\n rand_arr[i] = random()%256+1;\n \n // A random text, the range of its elements is 0-127\n char *tex = malloc((sizeof *tex) * …Run Code Online (Sandbox Code Playgroud) 抱歉,我一直不明白这里的规则。我已经删除了所有重复的帖子。这是第一个相关问题。\n请不要将此帖子标记为我另一篇帖子的重复(执行次数减少 3 倍,但执行效率几乎不变。在 C 中),即使代码有些相似,他们提出了截然不同的问题。这也是我同一天发现的两个问题。类似的帖子因“误判”而被重复,然后被关闭。可能是我没有把这个问题说清楚。我真的很希望得到答案,所以我重新发布了它。希望大家能够看清问题,非常感谢!
\n在下面的C代码中,我在第一次测试时间的循环中添加了一个“if”语句,执行时间完全相同。从理论上讲,它应该更慢。尽管分支预测可以使它们的性能几乎相同,但它实际上变得更快。这是什么原理呢?我尝试使用clang和gcc编译器分别在Mac和Linux环境中运行,并尝试了各种优化级别。为了防止缓存受到影响,我让速度较快的先执行,但有冗余代码的循环执行得更快。
\n如果您认为我的描述不可信,请将以下代码编译到您的计算机中并运行。希望有人能为我回答这个问题\xef\xbc\x8c谢谢。
\nC代码:
\n#include <stdio.h>\n#include <time.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define TLen 300000000\n#define SLen 10\n\nint main(int argc, const char * argv[]) {\n srandom((unsigned)time(NULL));\n \n // An array to increase the index,\n // the range of its elements is 1-256\n int rand_arr[128];\n for (int i = 0; i < 128; ++i)\n rand_arr[i] = random()%256+1;\n \n // A random text(very long), the range of its elements is 0-127\n char *tex = malloc((sizeof *tex) * …Run Code Online (Sandbox Code Playgroud)