相关疑难解决方法(0)

cout或printf这两者中的哪一个具有更快的执行速度C++?

我用C++编写了很长时间.我总是想知道哪个执行速度更快printf或者cout

情况:我正在用C++设计一个应用程序,我有一些约束,比如执行时间限制.我的应用程序在控制台上加载打印命令.那么哪一个更好printf或者cout

c++

24
推荐指数
5
解决办法
2万
查看次数

c ++ 11 Variadic Printf性能

可变参数模板在c ++ 11中引入.我发现可以使用它替换printf函数.但是,cout用于实现.我想知道是否有可能使用其他东西来实现类型安全但不牺牲太多性能.

void safe_printf(const char *s)
{
    while (*s) {
        if (*s == '%') {
            if (*(s + 1) == '%') {
                ++s;
            }
            else {
                throw "invalid format string: missing arguments";
            }
        }
        std::cout << *s++;
    }
}

template<typename T, typename... Args>
void safe_printf(const char *s, T& value, Args... args)
{
    while (*s) {
        if (*s == '%') {
            if (*(s + 1) == '%') {
                ++s;
            }
            else {
                std::cout << value;
                safe_printf(s + 1, args...); // …
Run Code Online (Sandbox Code Playgroud)

c++ formatting printf variadic-functions c++11

11
推荐指数
2
解决办法
2万
查看次数

造成这种差异的原因......从C++到C?

我想知道为什么会一直这样...... !! 我在c中编写了两个程序,在c ++中编写了另一个程序.两者都执行相同的操作.即打印1到2000000之间的数字.此外,我在执行开始时设置计时器..并且在打印之后还打印所有经过的时间.c ++程序所用的时间总是大于交流程序.我觉得时间差异很大.我很想知道这是什么原因.. ???? ..

这是两个程序

//iotest.c

#include<stdio.h>
#include<time.h>

clock_t start=clock();

int main()
{
for(int i=0;i<2000000;i++)

printf("%d\n",i);

printf("Time Elapsed: %f\n",((double)clock()-start)/CLOCKS_PER_SEC);

return 0;

}
Run Code Online (Sandbox Code Playgroud)

//iotest.cpp

#include<iostream>

#include<time.h>

using namespace std;

clock_t start=clock();

int main()
{
    for(int i=0;i<2000000;i++)

    cout<<i<<endl;

    cout<<"Time elapsed "<<((double)clock()-start)/CLOCKS_PER_SEC<<endl;

    return 0;

}
Run Code Online (Sandbox Code Playgroud)

// ver C++ 4.3.2通过发出命令编译c程序

g ++ iotest.c

执行给出

1

.

.

2000000

经过的时间:5.410000(并不总是相同..)

执行第二个程序

1

.

.

2000000

时间流逝:5.81(并非总是相同..)

c c++

5
推荐指数
3
解决办法
585
查看次数

为什么std :: cout这么耗时?

我已经制作了一个程序来计算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: …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

5
推荐指数
1
解决办法
2802
查看次数

标签 统计

c++ ×4

c++11 ×2

c ×1

formatting ×1

printf ×1

variadic-functions ×1