getchar_unlocked()–在C/C++中更快地输入进行竞争性编程

2021年4月11日15:41:04 发表评论 1,799 次浏览

getchar_unlocked()与getchar()类似, 但它不是线程安全的。以下是示例代码。

//A simple C program to demonstrate
//working of getchar_unlocked()
#include <stdio.h>
int main()
{
     //Syntax is same as getchar()
     char c = getchar_unlocked();
  
     printf ( "Entered character is %c" , c);
  
     return 0;
}
Input: g
Output: Entered character is g

以下是一些重要点:

由于它不是线程安全的, 因此可以避免所有互斥的开销, 并且它比getchar()更快。

对于具有"

警告:较大的I/O数据, 请谨慎使用某些语言(尽管如果算法设计良好, 大多数应该可以)

"。

即使在多线程环境中使用getchar_unlocked()也没有问题, 只要使用它的线程是唯一访问文件对象的线程

与getchar()的另一个区别是, 它不是C标准库函数, 而是POSIX函数。它可能不适用于基于Windows的编译器。

众所周知, scanf()比cin快, 而getchar()比scanf()快。 getchar_unlocked()比getchar()更快, 因此是最快的。

同样, 有getc_unlocked()putc_unlocked()和putchar_unlocked()分别是getc(), putc()和putchar()的非线程安全版本。

//A simple C program to demonstrate
//working of putchar_unlocked()
#include <stdio.h>
int main()
{
     //Syntax is same as getchar()
     char c = getchar_unlocked();
  
     putchar_unlocked(c);
  
     return 0;
}
Input: g
Output: g

作为练习, 读者可以尝试给出的解决方案这里使用getchar_unlocked()并将性能与getchar()进行比较。

本文作者:阿育什(Ayush Saluja)。如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: