执行时间以C++显示:cin/scanf/getchar_unlocked()
Execution time display in C++: cin/scanf/getchar_unlocked()
我正在做一个项目,以证明std::cin
在接受输入方面比scanf
慢,而反过来又比使用getchar/getchar_unlocked()
等通过自写函数获取输入要慢。
我想记录和打印每种情况下的执行时间,但我不知道如何应用时间和时间等头文件。
我将从 stdin 读取大量输入值,并希望显示每种情况下的执行时间。
请用一个简短的例子告诉我如何处理时间。
像这样的东西怎么样
auto start = std::chrono::high_resolution_clock::now();
some_long_running_operation();
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Operation took " <<
std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() <<
" microsecondsn";
(或多或少逐字摘自此参考资料及其子页面。更具体地说,从std::chrono::time_point
引用的第二个示例中,只是更改了使用的时钟。
代码的作用是从高分辨率时钟获取当前时间作为开始时间,执行要成为时间的操作,然后获取结束时间。然后,它以微秒为单位显示差异。
#include <time.h>
clock_t t;
void startTimer() {
t = clock();
}
void stopTimer() {
t = clock() - t;
printf("It took me %d clicks (%f seconds).n", t, ((float)t) / CLOCKS_PER_SEC);
}
然后根据需要调用这两个方法。
或
#include <sys/time.h>
#include <iostream>
using namespace std;
struct timeval t1, t2;
struct timezone tz;
void startTimer()
{
gettimeofday(&t1, &tz);
}
void stopTimer()
{
gettimeofday(&t2, &tz);
cout<<"It took "<< t2.tv_sec - t1.tv_sec <<" seconds and "<< t2.tv_usec - t1.tv_usec<<" microseconds"<<endl;;
}
// call "startTimer()" to start timer
// call "stopTimer()" to stop timer and print total time in microseconds.
相关文章:
- 如何使用 SIGINT 在第二个线程中断 getchar
- 如果输入缓冲区不为空,请使用getchar.()检测Ctrl+d
- getchar() 避免转义序列
- getchar() 函数如何输出
- Python 3中是否有内置功能,例如C 中的GetChar()
- 6031:在Visual Studio 2019中忽略了返回值(getchar())
- 无法使我的getChar()函数能够工作,我希望它能正常工作,输出IS10而不是2 C
- 使用getchar()获取字符并将其保存到每次C 的新行中的文件中
- 如何在不按 Enter 的情况下传递 getchar() 以使其自动?
- 从文件而不是getchar中获取字符
- 需要澄清 getchar() 和换行符
- 从 getchar 读取输入
- 为什么getchar()会阻塞所有线程
- 用"fprintf"打印错误后调用"getchar()"有什么意义?
- 使用getchar()函数
- omxplayer中复杂的getchar()操作
- SFML 2.1 getchar equivalent
- 了解 Getchar 已解锁
- getchar 有什么问题(因为程序在没有检查的情况下退出循环)
- 使用 getchar() 输入字符的最有效方法,就像 cin 中没有换行符和空格字符一样C++