这是一个通用的问题,以帮助有程序问题的新程序员,但不知道如何使用调试器来诊断问题的原因.
这个问题涉及两类更具体的问题:
[What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173)
我编写了一个简单的多线程程序,如下所示:
static bool finished = false;
int func()
{
size_t i = 0;
while (!finished)
++i;
return i;
}
int main()
{
auto result=std::async(std::launch::async, func);
std::this_thread::sleep_for(std::chrono::seconds(1));
finished=true;
std::cout<<"result ="<<result.get();
std::cout<<"\nmain thread id="<<std::this_thread::get_id()<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)
它通常表现在调试模式下在Visual Studio中或-O0在GC c和后打印出的结果1秒钟。但是它卡住了,在“ 释放”模式或中不打印任何内容-O1 -O2 -O3。
GCC,MSVC,LLVM以及可能的其他工具链支持链接时(整个程序)优化,以允许编译单元之间的调用优化.
在编译生产软件时是否有理由不启用此选项?
我在C中编写了以下代码.它非常简单,因为它恰好x为每个for循环进行了位移.
int main() {
int x = 1;
for (int i = 0; i > -2; i++) {
x >> 2;
}
}
Run Code Online (Sandbox Code Playgroud)
现在正在发生奇怪的是,当我刚刚编译它没有任何的优化或第一级优化(-O),它运行得很好(我定时可执行文件及其有关1.4s与-O和5.4s没有任何优化.
现在,当我添加-O2或-O3切换编译并为生成的可执行文件计时时,它不会停止(我已经测试过60s).
关于可能导致这种情况的任何想法?
这是我的代码。
foo()很简单。它将参数与一些字符串一一比较。
main()有点复杂。它只是foo()用不同的字符串调用并计时,3 次。
#include <string.h>
#include <time.h>
#include <stdio.h>
int foo(const char *s)
{
int r = 0;
if (strcmp(s, "a11111111") == 0) {
r = 1;
} else if (strcmp(s, "b11111111") == 0) {
r = 2;
} else if (strcmp(s, "c11111111") == 0) {
r = 3;
} else if (strcmp(s, "d11111111") == 0) {
r = 4;
} else if (strcmp(s, "e11111111") == 0) {
r = 5;
} else if (strcmp(s, …Run Code Online (Sandbox Code Playgroud) 我在llvm clang Apple LLVM 8.0.0版(clang-800.0.42.1)上反汇编代码:
int main() {
float a=0.151234;
float b=0.2;
float c=a+b;
printf("%f", c);
}
Run Code Online (Sandbox Code Playgroud)
我编译时没有-O规范,但我也试过-O0(给出相同)和-O2(实际上计算值并存储它预先计算)
产生的反汇编如下(我删除了不相关的部分)
-> 0x100000f30 <+0>: pushq %rbp
0x100000f31 <+1>: movq %rsp, %rbp
0x100000f34 <+4>: subq $0x10, %rsp
0x100000f38 <+8>: leaq 0x6d(%rip), %rdi
0x100000f3f <+15>: movss 0x5d(%rip), %xmm0
0x100000f47 <+23>: movss 0x59(%rip), %xmm1
0x100000f4f <+31>: movss %xmm1, -0x4(%rbp)
0x100000f54 <+36>: movss %xmm0, -0x8(%rbp)
0x100000f59 <+41>: movss -0x4(%rbp), %xmm0
0x100000f5e <+46>: addss -0x8(%rbp), %xmm0
0x100000f63 <+51>: movss %xmm0, -0xc(%rbp)
...
Run Code Online (Sandbox Code Playgroud)
显然它正在做以下事情:
c ×3
c++ ×2
gcc ×2
x86-64 ×2
assembly ×1
compilation ×1
data-race ×1
debugging ×1
llvm-codegen ×1
optimization ×1
performance ×1