我使用OpenMP并行程序,但它比单线程慢。我使用的代码是#pragma omp parallel for
。我不知道该怎么解决。我希望你能帮助我。谢谢!
我在子函数(xorencrypt
和xordecode
)中使用了OpenMP代码。我使用c99 -o NEWRSULT openMPtest.c -fopenmp
进行编译。该程序与密码学加密和解码有关
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <time.h>
int char_to_index(char c)
{
/*if(c>='A' && c<='Z'){
c=c+32;
}*/
char x = c;
char result = x - 'a';
return (int)result;
}
char index_to_char(int c)
{
int result = c + 97;
return (char)result;
}
char * xorencrypt(char * message, char * key) {
size_t messagelen = strlen(message);
size_t keylen = strlen(key);
char * encrypted = malloc(messagelen+1);
int i;
#pragma omp parallel for
for (i = 0; i < messagelen; i++) {
int buf1 = char_to_index(message[i]);
int buf2 = char_to_index(key[i % keylen]);
char r = index_to_char(buf1 ^ buf2);
encrypted[i] = r;
}
encrypted[messagelen] = '\0';
return encrypted;
}
char * xordecode(char * cript, char * key) {
size_t criptlen = strlen(cript);
size_t keylen = strlen(key);
char * message = malloc(criptlen+1);
int i;
#pragma omp parallel for
for (i = 0; i < criptlen; i++) {
int buf1 = char_to_index(cript[i]);
int buf2 = char_to_index(key[i % keylen]);
char r = index_to_char(buf1 ^ buf2);
message[i] = r;
}
message[criptlen] = '\0';
return message;
}
int main(int argc, const char * argv[]) {
clock_t start, end;
start = clock();
char * message = "Is this Rayban?";
printf("Input : %s\n",message);
char * key = "key";
char * encrypted = xorencrypt(message, key);
printf("Encrypted: %s\n", encrypted);
char * message1 = xordecode(encrypted, key);
printf("Decoded : %s\n", message1);
end = clock();
double diff = end - start; // ms
printf(" %f ms" , diff);
printf(" %f sec", diff / CLOCKS_PER_SEC );
return 0;
}