我编写了一个代码,通过两种方法将大量字母从小格式转换为大小格式。第一种方法,我使用逐位操作,第二种方法是使用switch语句。我的最终目标是使用此示例作为理解基准的参考。我应该在代码中考虑哪些参数来判断使用按位运算是否优于使用switch。到目前为止,我使用经过的时间作为更好性能的指标。在我的例子中,
Lower2UpperBitwise:
elapsed time: 0.655201s
Lower2UpperSwitch:
elapsed time: 3.30221s
我正在使用cygwin在Windows中运行代码,这是我的代码
#include <iostream>
#include <random>
#include <string>
#include <chrono>
void Lower2UpperBitwise(std::string& str)
{
int mask = 0xDF;
long i(0);
while ( i != (long)str.size() )
str[i++] &= mask;
}
void Lower2UpperSwitch(std::string& str)
{
for ( long i(0); i < (long)str.size(); ++i ){
switch(str[i]){
case 'a': str[i] = 'A'; break;
case 'b': str[i] = 'B'; break;
case 'c': str[i] = 'C'; break;
case 'd': str[i] = 'D'; break;
case 'e': str[i] = 'E'; break;
case 'f': str[i] = 'F'; break;
case 'g': str[i] = 'G'; break;
case 'h': str[i] = 'H'; break;
case 'i': str[i] = 'I'; break;
case 'j': str[i] = 'J'; break;
case 'k': str[i] = 'K'; break;
case 'l': str[i] = 'L'; break;
case 'm': str[i] = 'M'; break;
case 'n': str[i] = 'N'; break;
case 'o': str[i] = 'O'; break;
case 'p': str[i] = 'P'; break;
case 'q': str[i] = 'Q'; break;
case 'r': str[i] = 'R'; break;
case 's': str[i] = 'S'; break;
case 't': str[i] = 'T'; break;
case 'u': str[i] = 'U'; break;
case 'v': str[i] = 'V'; break;
case 'w': str[i] = 'W'; break;
case 'x': str[i] = 'X'; break;
case 'y': str[i] = 'Y'; break;
case 'z': str[i] = 'Z'; break;
default: break;
}
}
}
int main()
{
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
/* Setting up the random generator */
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> di(97,122); // (97 : a) (122 : z)
// string size: 200,000,000
const long SIZE( 200000000 );
std::string str;
//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
/* Fill string with random small letters (a-z) */
for (long i(0); i < SIZE; ++i) {
int temp = di(mt);
str.push_back( static_cast<char>(temp) );
}
/* =========================================== */
std::string temp;
temp = str;
std::chrono::time_point<std::chrono::system_clock> start, end;
std::chrono::duration<double> elapsed_seconds;
// Using bitwise operation )##################################
start = std::chrono::system_clock::now(); // <-- Start
Lower2UpperBitwise(temp); // <-- Run
end = std::chrono::system_clock::now(); // <-- End
elapsed_seconds = end-start;
std::cout << "\nLower2UpperBitwise:\n";
std::cout << " elapsed time: " << elapsed_seconds.count() << "s\n";
// Using Switch operation )#####################################
temp = str;
start = std::chrono::system_clock::now(); // <-- Start
Lower2UpperSwitch(temp); // <-- Run
end = std::chrono::system_clock::now(); // <-- End
elapsed_seconds = end-start;
std::cout << "\n Lower2UpperSwitch:\n";
std::cout << " elapsed time: " << elapsed_seconds.count() << "s\n";
return 0;
}
这是Makefile。
CXX = g++
CXXFLAGS = -std=c++11 -Wall -O3
TARGET = test
.PHONY: all
all: $(TARGET)
$(TARGET): main.o
$(CXX) $(CXXFLAGS) main.cpp -o $(TARGET)
.PHONY: clean
clean:
rm *.o $(TARGET)