我有一个2 GB的文件(iputfile.txt
),其中文件中的每一行都是一个单词,就像:
apple
red
beautiful
smell
spark
input
Run Code Online (Sandbox Code Playgroud)
我需要编写一个程序来读取文件中的每个单词并打印单词计数.我使用Java和C++编写它,但结果令人惊讶:Java运行速度比C++快2.3倍.我的代码如下:
C++:
int main() {
struct timespec ts, te;
double cost;
clock_gettime(CLOCK_REALTIME, &ts);
ifstream fin("inputfile.txt");
string word;
int count = 0;
while(fin >> word) {
count++;
}
cout << count << endl;
clock_gettime(CLOCK_REALTIME, &te);
cost = te.tv_sec - ts.tv_sec + (double)(te.tv_nsec-ts.tv_nsec)/NANO;
printf("Run time: %-15.10f s\n", cost);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
5e+08
Run time: 69.311 s
Run Code Online (Sandbox Code Playgroud)
Java的:
public static void main(String[] args) throws Exception {
long startTime = System.currentTimeMillis();
FileReader reader …
Run Code Online (Sandbox Code Playgroud) 我有一个X
像的张量[0.1, 0.5, -1.0, 0, 1.2, 0]
,我想实现一个名为 的函数filter_positive()
,它可以将正数据过滤成一个新的张量并返回原始张量的索引。例如:
new_tensor, index = filter_positive(X)
new_tensor = [0.1, 0.5, 1.2]
index = [0, 1, 4]
Run Code Online (Sandbox Code Playgroud)
如何在 pytorch 中最有效地实现此功能?
我的输入文件是2GB,在这个文件中每行都是一个单词.我需要写一个程序来做wordcount.我使用Java和C++来完成相同的任务,但结果令人惊讶:C++太慢了!我的代码如下:
C++:
int main() {
struct timespec ts, te;
double cost;
clock_gettime(CLOCK_REALTIME, &ts);
map<string, int> map;
ifstream fin("inputfile.txt");
string word;
while(getline(fin, word)) {
++map[word];
}
clock_gettime(CLOCK_REALTIME, &te);
cost = te.tv_sec - ts.tv_sec + (double)(te.tv_nsec-ts.tv_nsec)/NANO;
printf("cost: %-15.10f s\n", cost);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产出:成本:257.62秒
Java的:
public static void main(String[] args) throws Exception {
long startTime = System.currentTimeMillis();
Map<String, Integer> map = new HashMap<String, Integer>();
FileReader reader = new FileReader("inputfile.txt");
BufferedReader br = new BufferedReader(reader);
String str = null;
while((str = br.readLine()) != …
Run Code Online (Sandbox Code Playgroud)