Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
printf("%.2f\n", count * 100.0 / total);
std::cout << std::setprecision(2) << std::fixed << count * 100.0 / total << std::endl
#ifdef USE_SPRINTF
void outf ( char* out, float arg )
{
sprintf ( out, "%f", arg );
}
const char * sName = "Using sprintf res=%s\n";
#else
void outf ( char* out, float arg )
{
unsigned int x = arg;
arg -=x;
UItoA ( &out, x);
*out++='.';
x=arg*1000000;
UItoA ( &out, x);
*out++='\0';
}
const char * sName = "Using own UItoA res=%s\n";
#endif
int main(int argc, char *argv[])
{
float b;
b=3556.2323;
char cout[100];
int i;
for (i=0; i<100000000; ++i)
outf(cout,b);
printf (sName,cout);
return 0;
}
Что произойдёт, если я всё же включу её перед считыванием данных из файла?Простите — но с чем именно вы собрались синхронизировать файловый поток? Для синхронизации требуется два объекта. cin синхронизирован с stdin, cout — с stdout, а с чем будет синхронизирован созданный вами объект?
#include <stdio.h>
long read_batched(long *out)
{
char buf[20];
long c, x = 0, neg = 0;
char *res = fgets(buf, sizeof(buf), stdin);
if (res == NULL) return 0;
while ((c = *(res++)) != 0) {
if ('0' <= c && c <= '9') {
x = x*10 + c - '0';
} else if (c == '-') {
neg = 1;
} else {
break;
}
}
*out = neg ? -x : x;
return 1;
}
int main()
{
long x;
long max = -1;
while (read_batched(&x)) {
if (x > max) max = x;
}
printf("%ld\n", max);
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main()
{
long max = -1;
char buf[655360];
long c, x = 0, neg = 0, n, i;
while ((n = read(0, buf, sizeof(buf))) > 0) {
for (i = 0; i < n; i++) {
c = buf[i];
if ('0' <= c && c <= '9') {
x = (x<<1) + (x<<3) + c - '0';
} else if (c == '-') {
neg = 1;
} else { // newline
if (x > max) max = x;
x = 0;
neg = 0;
}
}
}
printf("%ld\n", max);
return 0;
}
x = (x<<1) + (x<<3) + c - '0';
leaq 0(,%rbx,8), %rcx
leaq (%rcx,%rbx,2), %rcx
leaq -48(%rax,%rcx), %rbx
x = x*10 + c - '0';
leaq (%rbx,%rbx,4), %rcx
leaq -48(%rax,%rcx,2), %rbx
cout << "Hello!".split, который выглядит как stringList = "a,b,cc,ddd" / ','. Почему нет? Мы же делим строку на части, так? Отличная метафора…Scanner, который является некоторым аналогом потока ввода из iostream. Получилась вот такая прога:package readnum;
import java.util.Scanner;
public class ReadNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0;
while (sc.hasNextInt()) {
int next = sc.nextInt();
if (next > max) {
max = next;
}
}
System.out.println("Max: " + max);
}
}
$ time java -cp bin readnum.ReadNum < data
Max: 999999
real 0m2.173s
user 0m0.031s
sys 0m0.015s
package readnum;
import java.util.Scanner;
public class ReadNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double max = 0;
while (sc.hasNextDouble()) {
double next = sc.nextDouble();
if (next > max) {
max = next;
}
}
sc.close();
System.out.println("Max: " + max);
}
}
$ time java -cp bin readnum.ReadNum < data
Max: 1.0E7
real 1m2.414s
user 0m0.015s
sys 0m0.031s
package readnum;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ReadNum {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
double max = 0;
while (sc.hasNextDouble()) {
double next = sc.nextDouble();
if (next > max) {
max = next;
}
}
sc.close();
System.out.println("Max: " + max);
}
}
$ time java -cp bin readnum.ReadNum < data
Max: 1.0E7
real 1m1.802s
user 0m0.015s
sys 0m0.015s
Scanner. Избавляемся от него:package readnum;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadNum {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double max = 0;
String line;
while ((line = br.readLine()) != null) {
double next = Double.parseDouble(line);
if (next > max) {
max = next;
}
}
br.close();
System.out.println("Max: " + max);
}
}
$ time java -cp bin readnum.ReadNum < data
Max: 1.0E7
real 0m2.222s
user 0m0.000s
sys 0m0.047s
Scanner никуда не годится. Тормозит жутко. Если мне надо будет прочитать гигабайт чисел из потока ввода, воспользуюст вашим кодом с getchar и JNI. Слава богу, в реальности таких задач немного :)import qualified Data.ByteString.Lazy.Char8 as B
import Data.Maybe
import Data.List
main = B.interact $ B.pack . show . foldl' max 0 . map (fst . fromJust . B.readInt) . B.lines
-O3
Optimize yet more. -O3 turns on all optimizations specified by -O2 and also turns on the -finline-functions, -funswitch-loops, -fpredictive-commoning, -fgcse-after-reload, -ftree-loop-vectorize, -ftree-loop-distribute-patterns, -ftree-slp-vectorize, -fvect-cost-model, -ftree-partial-pre and -fipa-cp-clone options.
#include <stdio.h>
#include <unistd.h>
int main()
{
long max = -1;
char buf[655361], *bufp;
long c, x = 0, n;
while ((n = read(0, buf, sizeof(buf) - 1)) > 0) {
buf[n] = 0;
bufp = buf;
while ((c = *(bufp++)) != 0) {
c -= '0';
if (c >= 0 && c <= 9) {
x = x*10 + c;
} else if (c == '\n' - '0') {
if (x > max) max = x;
x = 0;
}
}
}
printf("%ld\n", max);
return 0;
}
$ clang -o merhalak -O3 merhalak.c
$ time ./merhalak <ololo.txt
warning: this program uses gets(), which is unsafe.
683641836811
real 0m1.166s
user 0m1.123s
sys 0m0.037s
$ clang -o test -O3 test.c
$ time ./test <ololo.txt
683641836811
real 0m0.145s
user 0m0.118s
sys 0m0.025s
$ gcc-4.9 -o merhalak -O3 merhalak.c && time ./merhalak <ololo.txt
warning: this program uses gets(), which is unsafe.
683641836811
real 0m1.140s
user 0m1.104s
sys 0m0.033s
$ gcc-4.9 -o test -O3 test.c && time ./test <ololo.txt
683641836811
real 0m0.166s
user 0m0.140s
sys 0m0.024s
The headers <complex.h>, <stdatomic.h>, and <threads.h> are conditional features that implementations need not support; see 6.10.8.3.
$ seq 1000000 | time testNiostreams_performance.cpp:146:22: error: no member named 'stoi' in namespace 'std'
int x = std::stoi(line);
У меня с помощью getline+std::stod получается парсить в 2 раза быстрее, чем с помощью boost::spirit::qi… Конфигурация: MinGW 8.1 64 bit, C++17, boost 1.76. Файл содержит 2 миллиона триста тысяч строк, размер его — 365 мегабайт.
Насколько медленны iostreams?