在C中,为什么signed int速度比unsigned int?是的,我知道这个网站已被多次询问和回答(链接如下).但是,大多数人说没有区别.我编写了代码并意外地发现了显着的性能差异.
为什么我的代码的"未签名"版本比"签名"版本慢(即使在测试相同的数字时)?(我有一个x86-64英特尔处理器).
类似的链接
编译命令: gcc -Wall -Wextra -pedantic -O3 -Wl,-O3 -g0 -ggdb0 -s -fwhole-program -funroll-loops -pthread -pipe -ffunction-sections -fdata-sections -std=c11 -o ./test ./test.c && strip --strip-all --strip-unneeded --remove-section=.note --remove-section=.comment ./test
signed int 版注意:如果我明确声明signed int所有数字,则没有区别.
int isprime(int num) {
// Test if a signed int is prime
int i;
if (num % 2 == 0 || num % 3 == 0)
return 0;
else if (num % 5 == …Run Code Online (Sandbox Code Playgroud) 我正在创建一个基本的素数检查器,基于C - 确定一个数字是否为素数 ,但是使用OpenMP.
int isPrime(int value)
{
omp_set_num_threads(4);
#pragma omp parallel for
for( int j = 2; j * j <= value; j++)
{
if ( value % j == 0) return 0;
}
return value;
}
Run Code Online (Sandbox Code Playgroud)
使用-fopenmp进行编译时,GCC版本4.7.2 出错,说明invalid controlling predicatefor循环.
看起来这个错误是由for循环中的j平方引起的.有没有办法解决这个问题,仍然可以从算法中获得所需的输出?
我的问题是关于试验部门的条件测试.关于采用什么条件测试似乎存在争议.我们来看看RosettaCode的代码 .
int is_prime(unsigned int n)
{
unsigned int p;
if (!(n & 1) || n < 2 ) return n == 2;
/* comparing p*p <= n can overflow */
for (p = 3; p <= n/p; p += 2)
if (!(n % p)) return 0;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
车轮分解或使用预定的素数列表不会改变我的问题的本质.
我可以想到三种情况来进行条件测试:
案例1:适用于所有n但它必须在每次迭代时进行额外的除法(编辑:实际上它不需要额外的除法但它仍然较慢.我不知道为什么.请参阅下面的汇编输出).我发现它的速度是情况2的两倍,因为大的n值是素数(在我的Sandy Bridge系统上).
案例2:明显快于案例1,但它有一个问题,它溢出大n并进入一个不定式循环.它可以处理的最大值是
(sqrt(n) …Run Code Online (Sandbox Code Playgroud) int prime(unsigned long long n){
unsigned val=1, divisor=7;
if(n==2 || n==3) return 1; //n=2, n=3 (special cases).
if(n<2 || !(n%2 && n%3)) return 0; //if(n<2 || n%2==0 || n%3==0) return 0;
for(; divisor<=n/divisor; val++, divisor=6*val+1) //all primes take the form 6*k(+ or -)1, k[1, n).
if(!(n%divisor && n%(divisor-2))) return 0; //if(n%divisor==0 || n%(divisor-2)==0) return 0;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码是朋友为获得素数而写的东西.它似乎正在使用某种筛分,但我不确定它是如何起作用的.下面的代码是我不那么棒的版本.我会用sqrt我的循环,但我看到他做了其他事情(可能是筛选相关),所以我没有打扰.
int prime( unsigned long long n ){
unsigned i=5;
if(n < 4 && n > 0)
return 1;
if(n<=0 …Run Code Online (Sandbox Code Playgroud) 现在我在编译方面遇到了新代码的问题.我有两个很好的答案,但chux的答案是为了纠正我的代码.所以根据他/她的指示我的新代码是:
#include <math.h>
#include <conio.h>
int main()
{
int n,i,r;
printf("Enter A Number to know its prime or non prime");
scanf("%d",&n);
for(i=2;i<=n-1;i++)
{
if(n%i==0)
{r==1;
break;
}
}
if(r==1)
printf("%d is a non-prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但在输出上显示为87是素数.我不知道为什么.但有人能发现我的错误吗?