【发布时间】:2017-08-20 11:42:23
【问题描述】:
我编写了一个程序来计算 8 个字符的字符串“sharjeel”的排列。
#include <iostream>
#include <time.h>
char string[] = "sharjeel";
int len = 8;
int count = 0;
void swap(char& a, char& b){
char t = a;
a = b;
b = t;
}
void permute(int pos) {
if(pos==len-1){
std::cout << ++count << "\t" << string << std::endl;
return;
}
else {
for (int i = pos; i < len;i++)
{
swap(string[i], string[pos]);
permute(pos + 1);
swap(string[i], string[pos]);
}
}
}
int main(){
clock_t start = clock();
permute(0);
std::cout << "Permutations: " << count << std::endl;
std::cout << "Time taken: " << (double)(clock() - start) / (double)CLOCKS_PER_SEC << std::endl;
return 1;
}
如果我打印每个排列,执行完成大约需要 9.8 秒。
40314 lshaerej
40315 lshareej
40316 lshareje
40317 lshareej
40318 lshareje
40319 lsharjee
40320 lsharjee
Permutations: 40320
Time taken: 9.815
现在如果我换行:
std::cout << ++count << "\t" << string << std::endl;
用这个:
++count;
然后重新编译,输出为:
Permutations: 40320
Time taken: 0.001
再次运行:
Permutations: 40320
Time taken: 0.002
使用带有 -O3 的 g++ 编译
为什么 std::cout 相对比较耗时?有没有更快的打印方法?
编辑:制作了程序的 C# 版本
/*
* Permutations
* in c#
* much faster than the c++ version
*/
using System;
using System.Diagnostics;
namespace Permutation_C
{
class MainClass
{
private static uint len;
private static char[] input;
private static int count = 0;
public static void Main (string[] args)
{
Console.Write ("Enter a string to permute: ");
input = Console.ReadLine ().ToCharArray();
len = Convert.ToUInt32(input.Length);
Stopwatch clock = Stopwatch.StartNew();
permute (0u);
Console.WriteLine("Time Taken: {0} seconds", clock.ElapsedMilliseconds/1000.0);
}
static void permute(uint pos)
{
if (pos == len - 1u) {
Console.WriteLine ("{0}.\t{1}",++count, new string(input));
return;
} else {
for (uint i = pos; i < len; i++) {
swap (Convert.ToInt32(i),Convert.ToInt32(pos));
permute (pos + 1);
swap (Convert.ToInt32(i),Convert.ToInt32(pos));
}
}
}
static void swap(int a, int b) {
char t = input[a];
input[a] = input[b];
input[b] = t;
}
}
}
输出:
40313. lshaerje
40314. lshaerej
40315. lshareej
40316. lshareje
40317. lshareej
40318. lshareje
40319. lsharjee
40320. lsharjee
Time Taken: 4.628 seconds
Press any key to continue . . .
从这里开始,与 std::cout 的结果相比,Console.WriteLine() 似乎快了近一倍。什么似乎在减慢 std::cout 的速度?
【问题讨论】:
-
您在每次排列时刷新缓冲区。请使用
'\n'而不是std::endl重试。尽管如此,由于答案中解释的原因,它会变慢,但您可能会观察到加速。 -
考虑使用
std::ios_base::sync_with_stdio。请禁用printf和std::cout之间的同步。 -
@nos 没有优化'耗时:0.001'
-
有趣的是 C# 版本更快 - Console.WriteLine 阻塞,直到输出被完全写入:stackoverflow.com/questions/3670057/… C++ 可能发生类似(但更慢)的事情