gpt4 book ai didi

c++ - 造成这种差异的原因……从 C++ 到 C?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:48:57 25 4
gpt4 key购买 nike

我想知道为什么这种情况一直发生...!!我写了两个程序,一个用c,另一个用c++。两者执行相同的操作。即打印从 1 到 2000000 的数字。此外,我在执行开始时设置计时器。在打印所有数字后,还打印了耗时。C++ 程序的运行时间总是大于 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;

}

//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;

}

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

g++ iotest.c

执行给

1

.

.

2000000

耗时:5.410000(不总是相同..)

执行第二个程序

1

.

.

2000000

耗时:5.81(不总是相同的..)

最佳答案

这两个程序的区别在于 C++ 版本使用 endl,它不仅插入换行符而且刷新缓冲区。执行任何输出的缓慢部分是刷新缓冲区。

如果您使用 C++ 程序,这两个程序的速度可能大致相同

count << i << "\n";

以下两个程序实现了相似的执行时间:

C 程序 (a.c):

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

int main()
{
clock_t start=clock();
for (int i=0; i<2000000; i++) printf("%d\n",i);
clock_t end=clock();

fprintf(stderr, "Time Elapsed: %f\n",((double)end-start)/CLOCKS_PER_SEC);
return 0;
}

编译:gcc -O3 -std=c99 a.c

C++ 程序 (b.cpp):

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
clock_t start=clock();
for (int i=0;i<2000000;i++) cout << i << '\n';
clock_t end=clock();

cerr << "Time elapsed " << ((double)end-start)/CLOCKS_PER_SEC << endl;

return 0;
}

g++ -O3 b.cpp编译

关于c++ - 造成这种差异的原因……从 C++ 到 C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5180675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com